Problem overview
The function threeSum receives a slice of integers, nums, and returns every triplet [nums[i], nums[j], nums[k]] from three different indices whose values add up to 0. The answer must not contain duplicate triplets: the same three values count once, whichever indices they come from. Each triplet is written in ascending order, and the triplets are returned 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, 1, 1] it is [], because the only triplet adds up to 2. For [0, 0, 0, 0] it is [[0, 0, 0]]: four zeros give several index choices, but they all make the same triplet.
The budget is O(n²) time. The extra space is O(1), not counting the sort and the triplets that are returned.
Approach: sort, fix one number, squeeze the other two
Trying every triple of indices is O(n³), too slow for 3,000 elements, and removing duplicates from it needs extra work. Sorting changes the problem in three ways:
- Equal values sit side by side, so repeats are easy to recognise and skip.
- If a triplet is collected with
i < left < right, its values are already in ascending order. - Scanning from left to right produces the triplets in ascending order, so no sorting is needed at the end.
Then fix the first number, nums[i], and look for two numbers to its right that add up to -nums[i]. That is a two-pointer search: left starts just after i and right at the last index. If the total of the three numbers is negative, it is too small, and the only way to raise it is to move left to a bigger value. If it is positive, move right to a smaller value. If it is zero, record the triplet. Each pointer only moves one way, so one value of i costs O(n), and the whole search O(n²).
Duplicates are handled in two places: a first number equal to the previous one is skipped, and after a hit, left skips over equal values.
Step by step
- Sort
numswithsort.Ints, which sorts a slice ofintin place. - Store the length in
n. - Create
resultas an empty[][]int. Each element is one triplet. - Loop
ifrom 0 whilei < n-2. The other two numbers sit to the right ofi, so it stops two places before the end. - Skip repeated first numbers: if
i > 0andnums[i] == nums[i-1],continue. The same first number would find the same triplets again. - Set the pointers:
leftisi+1andrightisn-1. - Loop while
left < right. When the pointers meet, every pair for thisihas been checked. - Compute
totalasnums[i] + nums[left] + nums[right]. - If
total < 0, incrementleft. - Else if
total > 0, decrementright. - Otherwise the total is 0. Append the triplet
[]int{nums[i], nums[left], nums[right]}toresult, storing whatappendreturns. - Move both pointers inward. Moving only one would need the other's old value again, which gives the same triplet.
- Skip equal second numbers: while
left < rightandnums[left] == nums[left-1], incrementleft. The same second number would build the same triplet. - Return
resultafter the loops.
right needs no skipping loop of its own. After a hit, left holds a bigger value, so an old value at right makes the total positive, and the branch for a positive total moves right by itself.
The solution in Go
The function uses the sort package. The lesson already imports it; in a Go file of your own, add import "sort" at the top.
func threeSum(nums []int) [][]int {
sort.Ints(nums)
n := len(nums)
result := [][]int{}
for i := 0; i < n-2; i++ {
if i > 0 && nums[i] == nums[i-1] {
continue
}
left, right := i+1, n-1
for left < right {
total := nums[i] + nums[left] + nums[right]
if total < 0 {
left++
} else if total > 0 {
right--
} else {
result = append(result, []int{nums[i], nums[left], nums[right]})
left++
right--
for left < right && nums[left] == nums[left-1] {
left++
}
}
}
}
return result
}
The Go details worth a closer look:
sort.Intssorts the caller's slice. It reorders the elements in place, so after the call the caller'snumsis sorted too. For[3, -1, 2, -2, 0]the caller's slice ends up as[-2, -1, 0, 2, 3]. If the original order matters, sort a copy.- Go's while loop.
for left < right { ... }is aforwith only a condition. Go has nowhilekeyword. result := [][]int{}is an empty slice of slices. When there are no triplets, the function returns it as it is, an empty slice of length 0, which prints as[].appendreturns the slice. The result must be assigned back, as inresult = append(result, ...). The triplet[]int{...}is a new slice for each hit, so the stored triplets don't share memory.- Multiple declaration.
left, right := i+1, n-1declares both pointers on one line. - The bound
n-2is safe becausenis anint. The constraints guarantee at least 3 elements, so it is never negative.
Complexity
Time: O(n²). Sorting costs O(n log n). Then each of the at most n values of i runs a two-pointer scan in which left and right together move at most n steps, so the scans cost O(n²) in total, which dominates.
Space: O(1) extra, apart from the sort and the returned triplets. The scan uses only a few integers.
Edge cases and common mistakes
- All zeros.
[0, 0, 0, 0]gives[[0, 0, 0]]. After the first hit,leftskips the equal zeros, and the nextiis skipped as a repeat. - No triplet.
[0, 1, 1]gives[]. - Repeated first numbers. In
[-2, 0, 0, 2, 2]the answer is only[[-2, 0, 2]], even though the two 0s and the two 2s allow several index choices. - A triplet with a repeated value.
[-1, -1, 2]is a valid triplet in the first example, because the two -1s are different elements. The solution finds it: the first -1 is the fixed number, and the second one is reached byleft. Only a fixed number that repeats the one just before it is skipped. - Forgetting to skip duplicates. Without the two skips, the same triplet appears more than once whenever the input has repeated values.
- Not sorting. The two pointers rely on the order. The moves "bigger at
left" and "smaller atright" make no sense on an unsorted slice. - Skipping with
nums[i] == nums[i+1]. This would skip the first copy of a repeated value, and triplets that need two equal first values, such as[-1, -1, 2], would be lost. Comparing with the previous element,nums[i-1], keeps the first copy.
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, 0, 2, 2]gives[[-2, 0, 2]].[-100000, 0, 100000]gives[[-100000, 0, 100000]].[-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6]gives[[-4, -2, 6], [-4, 0, 4], [-4, 1, 3], [-4, 2, 2], [-2, -2, 4], [-2, 0, 2]].
