‹ DS&A interview · Socratic
DSA · Arrays & Two Pointers · #32

3Sum

Module 40 · difficulty 3/5·30:00starts on first keystroke

Given an integer array `nums`, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i`, `j`, and `k` are distinct indices and `nums[i] + nums[j] + nums[k] === 0`. The solution set must not contain duplicate triplets. Two triplets are considered duplicates if they contain the same multiset of values. Implement `threeSum(nums)` which returns an array of triplets. The order of the triplets and the order of values within each triplet do not matter.

Examples
  • nums = [-1, 0, 1, 2, -1, -4] [[-1, -1, 2], [-1, 0, 1]]The triplets sum to 0; duplicate triplets are excluded.
  • nums = [0, 1, 1] []No triplet sums to 0.
  • nums = [0, 0, 0] [[0, 0, 0]]Only one valid triplet exists.
Constraints
  • · 3 <= nums.length <= 3000
  • · -10^5 <= nums[i] <= 10^5
  • · The returned set must not contain duplicate triplets.
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.