Start learning free

LESSON 65 OF 314 · TWO POINTERS

3Sum in Go: O(n²) with Sorting and Two Pointers

Practice O(n2) Read the full explanation

You get an array of integers nums.

Return every triplet of numbers that adds up to 0. The three numbers must come from three different positions.

List each triplet of values once. Two triplets with the same three values count as one, even if they come from different positions.

Write each triplet from its smallest value to its largest. Then list the triplets from smallest to largest. Compare their first values, then their second, then their third.

If you sort nums first and collect the triplets from left to right, they come out in this order.

 

Example 1:

Input: nums = [3,-2,-1,1,-2,4]
Output: [[-2,-2,4],[-2,-1,3]]
Explanation:
(-2) + (-2) + 4 = 0 uses both -2s (positions 1 and 4).
(-2) + (-1) + 3 = 0 works with either -2. It is listed once.
Both triplets start with -2.
Their second values are -2 and -1.
Since -2 is smaller, the triplet with both -2s comes first.

Example 2:

Input: nums = [5,-1,2,7]
Output: []
Explanation: No three of these numbers add up to 0.

Example 3:

Input: nums = [1,-1,0,1,-1,0]
Output: [[-1,0,1]]
Explanation: Many choices of positions give (-1) + 0 + 1 = 0.
They all use the same values, so the triplet appears once.
[0,0,0] would need three zeros. There are only two.

 

Constraints:

  • 3 to 3,000 numbers.
  • Each number is from -100,000 to 100,000.

Note:

Your algorithm should run in O(n2) time and use O(1) extra space, apart from sorting and the triplets it returns.

STEP 1 OF 15
    Ctrl + Enter to check

    GO · TWO POINTERS

    3sum in Go, explained

    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

    1. Sort nums with sort.Ints, which sorts a slice of int in place.
    2. Store the length in n.
    3. Create result as an empty [][]int. Each element is one triplet.
    4. Loop i from 0 while i < n-2. The other two numbers sit to the right of i, so it stops two places before the end.
    5. Skip repeated first numbers: if i > 0 and nums[i] == nums[i-1], continue. The same first number would find the same triplets again.
    6. Set the pointers: left is i+1 and right is n-1.
    7. Loop while left < right. When the pointers meet, every pair for this i has been checked.
    8. Compute total as nums[i] + nums[left] + nums[right].
    9. If total < 0, increment left.
    10. Else if total > 0, decrement right.
    11. Otherwise the total is 0. Append the triplet []int{nums[i], nums[left], nums[right]} to result, storing what append returns.
    12. Move both pointers inward. Moving only one would need the other's old value again, which gives the same triplet.
    13. Skip equal second numbers: while left < right and nums[left] == nums[left-1], increment left. The same second number would build the same triplet.
    14. Return result after 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.Ints sorts the caller's slice. It reorders the elements in place, so after the call the caller's nums is 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 a for with only a condition. Go has no while keyword.
    • 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 [].
    • append returns the slice. The result must be assigned back, as in result = 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-1 declares both pointers on one line.
    • The bound n-2 is safe because n is an int. 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, left skips the equal zeros, and the next i is 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 by left. 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 at right" 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]].
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free