Problem overview
The method threeSum receives a list of integers, nums, and returns every triplet [nums[i], nums[j], nums[k]] where i, j and k are three different indices and the three values add up to 0. The answer must not contain duplicates: triplets made of the same three values count once, whichever indices they come from. Each triplet is written in ascending order, and the triplets are listed in ascending order too, comparing first values, then second, then third.
For nums = [-1, 0, 1, 2, -1, -4] the answer is [[-1, -1, 2], [-1, 0, 1]]. For [0, 0, 0, 0] it is [[0, 0, 0]]: several index choices give 0 + 0 + 0, but they all form the same triplet. The lesson asks for O(n²) time and no extra space beyond sorting and the output.
Approach: sort, fix one number, squeeze the other two
Trying every triple of indices is O(n³), and with up to 3000 numbers that is far too slow. Removing duplicates from the result afterwards would need extra bookkeeping as well.
Sorting the list first makes both problems easy. For each choice of the first number nums[i], the other two must be found among the elements to its right, and they must sum to -nums[i]. That is the two-pointer technique on a sorted list: put left just after i and right at the end, and look at the total:
- If the total is below 0, it is too small. The only way to raise it is to move
leftright, to a bigger value. - If the total is above 0, it is too big, and moving
rightleft gives a smaller value. - If the total is 0, the triplet is recorded and both pointers move inward.
Each pointer only moves one way, so the scan for one value of i takes O(n) steps, and over all values of i the work is O(n²).
Sorting also puts equal values side by side, so repeats are easy to skip. The sorted list is scanned from left to right, with i < left < right, so every triplet comes out already in ascending order, and the triplets themselves come out in ascending order.
On [-1, 0, 1, 2, -1, -4], the sorted list is [-4, -1, -1, 0, 1, 2]. With i at the first -1, the pointers find -1 + -1 + 2 and then -1 + 0 + 1. The second -1 is skipped as a first number, because it would repeat the same search.
Step by step
- Sort
numswith itssort()method. - Store the length in
n. - Create an empty
result. Because the list is sorted and scanned left to right, triplets are appended in the required order. - Fix the first number with
iinrange(n - 2). The other two numbers sit to its right, soistops two places before the end. - Skip a repeated first number: if
i > 0andnums[i] == nums[i - 1],continue. The same first value would find the same triplets again. - Set the pointers:
leftisi + 1andrightisn - 1. - Loop while
left < right. When they meet, every pair for thisihas been checked. - Compute
totalasnums[i] + nums[left] + nums[right]. - Total below 0: move
leftright. - Total above 0: move
rightleft. - Total equal to 0: append
[nums[i], nums[left], nums[right]]toresult. - Move both pointers inward. Keeping one in place would need the other's old value again, and that gives the same triplet.
- Skip repeated second numbers: while
left < rightandnums[left] == nums[left - 1], moveleftright. - Return
result.
The loop for right is not needed. After left moves to a new value, an old value at right would make the total too big, and the "above 0" branch moves right by itself.
The solution in Python
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
n = len(nums)
result = []
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, n - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total < 0:
left += 1
elif total > 0:
right -= 1
else:
result.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
return result
The Python details that matter here:
nums.sort()sorts in place and returnsNone. It changes the caller's list, which is allowed here.sorted(nums)would return a new list and leave the original alone, at the cost ofO(n)extra space.range(n - 2)is empty for fewer than three elements, so a short list returns[]without special handling.continueskips the rest of the loop body and goes on with the nexti.- The triplet is a new list each time. The expression
[nums[i], nums[left], nums[right]]copies the three values, so later pointer moves do not change what was stored. - Variable name
total. Avoid calling itsum, which would hide Python's built-in function.
Complexity
Time: O(n²). Sorting costs O(n log n). After that, each value of i runs a two-pointer scan in which left and right together move at most n steps, so the loops cost O(n²). That outweighs the sort.
Space: O(1) extra, apart from the sort and the returned triplets. The method keeps a few integers.
Edge cases and common mistakes
- Many equal values.
[0, 0, 0, 0]gives one triplet,[[0, 0, 0]]. The first zero is used asi, and the other zeros are skipped as first numbers. - Exactly three elements.
[0, 0, 0]gives[[0, 0, 0]], and[1, 2, -3]gives[[-3, 1, 2]], because the sort puts the values in ascending order. - No answer.
[0, 1, 1]gives[]. - A repeated value inside a triplet is fine.
[-2, 0, 1, 1, 2]gives[[-2, 0, 2], [-2, 1, 1]]. The repeated 1 is used twice, because those are two different indices. Only repeats at the same position in a triplet are skipped. - Skipping with the wrong neighbour. Comparing
nums[i]withnums[i + 1]would skip the first copy and lose triplets like[-1, -1, 2]. Comparing with the previous element keeps the first copy. - Not moving the pointers after a match leaves the loop running on the same triplet forever. Both must move.
Testing
[-1, 0, 1, 2, -1, -4]gives[[-1, -1, 2], [-1, 0, 1]].[0, 1, 1]gives[].[0, 0, 0, 0]gives[[0, 0, 0]].[-2, 0, 1, 1, 2]gives[[-2, 0, 2], [-2, 1, 1]].[1, 2, -3]gives[[-3, 1, 2]].
