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
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?
Sources and provenance
Full interview answer 25 min read
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.
Finish the outer scanIndices 4 and 5 have fewer than two values to their right, so their while loops never run. The two recorded triples are the complete unique answer.
-40-11-1203remaining fixed values1425
remainingi=4 and i=5: L is not less than Rresult[[-1, -1, 2], [-1, 0, 1]]
remaining fixed values
3→4
L
4→not shown
R
5→not shown
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
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.
Finish the outer scanIndices 4 and 5 have fewer than two values to their right, so their while loops never run. The two recorded triples are the complete unique answer.
-40-11-1203remaining fixed values1425
remainingi=4 and i=5: L is not less than Rresult[[-1, -1, 2], [-1, 0, 1]]
remaining fixed values
3→4
L
4→not shown
R
5→not shown
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 value
Pair totals/results
-4
Totals -3, -3, -2, -1; exhaust the pair interval
First -1
Emit [-1, -1, 2], then [-1, 0, 1]
Second -1
Skip repeated fixed value
0
Total 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 O(n2) under ordinary comparison/arithmetic costs.
Python sorting can use O(n) temporary workspace; m emitted triples need O(m) 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. The main input yields the same two triples and retains its original values and order.
Use when. Mutation permission changes. The copy adds O(n) 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.