Skip to content
mlmentorship

3Sum

Return every unique group of three numbers whose sum is zero.

Published · 25 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

3Sum

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A list of integers nums, possibly containing negatives and repeated values. Output. Return all distinct value triples whose sum is zero, not triples of indices. Rules. Each triple must use three distinct input positions. Repeated values are allowed when enough positions contain them. Do not repeat a value combination; the order of returned triples does not matter. The reference may reorder nums in place. Fewer than three values return []. Example. [-1, 0, 1, 2, -1, -4] returns [[-1, -1, 2], [-1, 0, 1]]. The two copies of -1 occupy different positions. [0, 0, 0, 0] returns only [[0, 0, 0]].

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

After sorting and fixing one value, pointer moves discard pairs that cannot sum to its complement.

Problem trace

Sorted order rules out a whole row of pairs

Worked example: one comparison rejects a whole row of pairsWith fixed -4 and left -2, even partner 2 gives -4. Every smaller partner also fails, so discard that left value.Fixed -4 and left -2: even thelargest partner fails1-52-4Add -6 to each partnerLargest possible sum -4 is belowtarget 0.-5-40
Read it this way: With fixed -4 and left -2, even partner 2 gives -4. Every smaller partner also fails, so discard that left value. If the largest available partner still gives a negative sum, can a smaller partner make this fixed pair reach zero?
Full interview answer 25 min read
Reading depth

Find every distinct combination of three input values whose sum is zero.

Problem

Input. A list of integers nums, possibly containing negatives and repeated values.

Output. Return all distinct value triples whose sum is zero, not triples of indices.

Rules. Each triple must use three distinct input positions. Repeated values are allowed when enough positions contain them. Do not repeat a value combination; the order of returned triples does not matter. The reference may reorder nums in place. Fewer than three values return [].

Example. [-1, 0, 1, 2, -1, -4] returns [[-1, -1, 2], [-1, 0, 1]]. The two copies of -1 occupy different positions. [0, 0, 0, 0] returns only [[0, 0, 0]].

Picture: Fix One Value, Eliminate Impossible Pairs

Problem trace

Sorted order rules out a whole row of pairs

Input and goalReturn every unique group of three numbers whose sum is zero.
Sort and test first -4Sort the input and fix -4. The smallest left value with the largest right value still gives a low total.
fixed i=0-40L=1-11-120314R=525
coveredRangepair search [1..5]total-4 + -1 + 2 = -3 < 0moveL: 1 -> 2
Sorted pair range 1 through 5 with fixed index 0. The selected sum is -3. Even the largest remaining partner is too small for this left value; the entire left row of pairs is rejected.-40-11-12031425-4 + -1 + 2 = -3 < 0Every pair using this L is too small(1,2) (1,3) (1,4) (1,5)
fixed i
0
L
1
R
5

Recognize it
The result needs unique triples satisfying a sum equation; sorting is allowed, and fixing one member reduces the remaining choice to a pair with an ordered sum.
Keep true
For a fixed index, every pair outside [L, R] is already emitted or safely discarded. If the total is low, no pair using the current L can work; if high, no pair using the current R can work.
Reuse it
After sorting, fix enough values to reduce k-sum to 2-sum, then use order to discard an entire boundary at once; carry duplicate-skipping rules at every fixed level.
Sort the input and fix -4. The smallest left value with the largest right value still gives a low total. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does moving L after a low sum discard no solution? Why is the second fixed -1 skipped?
Reference drawing

Problem trace

Sorted order rules out a whole row of pairs

Worked example: one comparison rejects a whole row of pairsWith fixed -4 and left -2, even partner 2 gives -4. Every smaller partner also fails, so discard that left value.Fixed -4 and left -2: even thelargest partner fails1-52-4Add -6 to each partnerLargest possible sum -4 is belowtarget 0.-5-40
Execution trace
Input and goalReturn every unique group of three numbers whose sum is zero.
Sort and test first -4Sort the input and fix -4. The smallest left value with the largest right value still gives a low total.
fixed i=0-40L=1-11-120314R=525
coveredRangepair search [1..5]total-4 + -1 + 2 = -3 < 0moveL: 1 -> 2
Sorted pair range 1 through 5 with fixed index 0. The selected sum is -3. Even the largest remaining partner is too small for this left value; the entire left row of pairs is rejected.-40-11-12031425-4 + -1 + 2 = -3 < 0Every pair using this L is too small(1,2) (1,3) (1,4) (1,5)
fixed i
0
L
1
R
5

Recognize it
The result needs unique triples satisfying a sum equation; sorting is allowed, and fixing one member reduces the remaining choice to a pair with an ordered sum.
Keep true
For a fixed index, every pair outside [L, R] is already emitted or safely discarded. If the total is low, no pair using the current L can work; if high, no pair using the current R can work.
Reuse it
After sorting, fix enough values to reduce k-sum to 2-sum, then use order to discard an entire boundary at once; carry duplicate-skipping rules at every fixed level.
Sort the input and fix -4. The smallest left value with the largest right value still gives a low total. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does moving L after a low sum discard no solution? Why is the second fixed -1 skipped?
Read it this way: With fixed -4 and left -2, even partner 2 gives -4. Every smaller partner also fails, so discard that left value. If the largest available partner still gives a negative sum, can a smaller partner make this fixed pair reach zero?

Sorted input is [-4, -1, -1, 0, 1, 2]. The trace’s fixed i, L, R correspond to index, left, right.

Fixed valuePair totals/results
-4Totals -3, -3, -2, -1; exhaust the pair interval
First -1Emit [-1, -1, 2], then [-1, 0, 1]
Second -1Skip repeated fixed value
0Total 3 is too high; no result

If the total is low even with the largest remaining right partner, no solution can use the current left value. Symmetrically, a high total with the smallest remaining left partner rules out the current right value. Each move preserves all unreported value triples; pointer crossing exhausts that fixed value.

Skip repeated fixed values. After a hit, skip copies of its successful left value: its required right value is already determined.

Code

def three_sum(nums: list[int]) -> list[list[int]]:
   nums.sort()
   answer: list[list[int]] = []

   for index, first in enumerate(nums):
      if index > 0 and first == nums[index - 1]:
         continue

      left, right = index + 1, len(nums) - 1
      while left < right:
         total = first + nums[left] + nums[right]
         if total < 0:
            left += 1
         elif total > 0:
            right -= 1
         else:
            answer.append([first, nums[left], nums[right]])
            left += 1
            right -= 1
            while left < right and nums[left] == nums[left - 1]:
               left += 1

   return answer

Pair work is under ordinary comparison/arithmetic costs. Python sorting can use temporary workspace; emitted triples need output space. The pointer scan alone uses constant state, not the whole implementation.

Change 1: Change the Target

New task. Return unique triples summing to any target.

Picture and change. Compare every total with target; preserve sorted elimination and duplicate rules.

Code. This replacement uses a sorted copy:

def three_sum_target(nums, target):
   values = sorted(nums)
   answer = []
   for index, first in enumerate(values):
      if index and first == values[index - 1]:
         continue
      left, right = index + 1, len(values) - 1
      while left < right:
         total = first + values[left] + values[right]
         if total < target:
            left += 1
         elif total > target:
            right -= 1
         else:
            answer.append([first, values[left], values[right]])
            left += 1
            right -= 1
            while left < right and values[left] == values[left - 1]:
               left += 1
   return answer

Check. [1, 2, 2, 3, 4], target 7, returns [[1, 2, 4], [2, 2, 3]].

Use when. The equation changes, not the ordered elimination proof.

Change 2: Preserve Input Order

New task. The caller needs the original order after the call.

Picture and change. Copy before the retained reference sorts.

Code. Place after three_sum:

def three_sum_preserving(nums):
   return three_sum(list(nums))

Check. The main input yields the same two triples and retains its original values and order.

Use when. Mutation permission changes. The copy adds storage.

Failure: Confusing Values With Indices

[0, 0, 0, 0] returns one value triple, not four index combinations.

Transfer Check

Why is advancing left safe after a low total?

Reasoned Answer

The current right value is already the largest available partner. Any smaller partner makes this left value no better.

Why Duplicate Skipping Preserves Completeness

For fixed first and left value, the required right value is uniquely determined by the sum equation. More positions containing those same values cannot create a new value triple. For a new fixed value, the two-pointer scan starts over its entire remaining suffix.

The reference mutates with nums.sort(); the target variant uses sorted(nums) and the preservation wrapper copies first. Test both output and input state. A correct result alone does not establish mutation compliance.

Returning original index triples would require different tracking and output-size accounting. See Two Sum for an index-witness contract; its one-index map does not enumerate unique three-value results automatically.