Start learning free

LESSON 65 OF 314 · TWO POINTERS

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

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

    SWIFT · TWO POINTERS

    3sum in Swift, explained

    Problem overview

    The method threeSum receives an array of integers, nums, and returns every triplet of values that adds up to 0, using three different indices. The answer must not contain the same triplet twice, however many index choices produce it. Each triplet is written in ascending order, and the triplets themselves are in ascending order too, comparing first values, then second, then third. The statement asks for O(n²) time and O(1) extra space, not counting the sort and the returned triplets.

    For [-1, 0, 1, 2, -1, -4] the answer is [[-1, -1, 2], [-1, 0, 1]]. Several index choices give [-1, 0, 1], since the array holds two -1s, but it appears once. For [0, 0, 0, 0] the answer is [[0, 0, 0]].

    Approach: fix one number, then squeeze two pointers

    Trying every triple of indices takes O(n³), and removing duplicates would need extra bookkeeping. Sorting first changes the problem in two ways.

    • Equal values sit side by side, so repeats are easy to skip.
    • For a fixed first number, finding the other two becomes a search for a pair with a given sum in a sorted range, which two pointers do in one pass.

    For each first number nums[i], one pointer left starts right after i and another, right, at the last index. Their sum with nums[i] is total:

    • If total is below 0, the sum is too small, and the only way to raise it is a bigger value at left, so left moves right.
    • If it is above 0, right moves left to lower it.
    • If it is 0, record the triplet and move both pointers inward.

    Each pointer only moves one way, so one first number costs O(n), and the whole method costs O(n²). Because the array is sorted and the scan goes left to right, the triplets are found already in the order the statement asks for, so no final sort is needed.

    Here is the scan on the sorted array [-4, -1, -1, 0, 1, 2]:

    i=0 left=1 right=5 total=-3
    i=0 left=2 right=5 total=-3
    i=0 left=3 right=5 total=-2
    i=0 left=4 right=5 total=-1
    i=1 left=2 right=5 total=0
    i=1 left=3 right=4 total=0
    i=2 skipped
    i=3 left=4 right=5 total=3
    

    For i = 0 the sum never reaches 0, so nothing is found. For i = 1 both lines with total 0 are triplets: [-1, -1, 2] and [-1, 0, 1]. Index 2 holds -1 again, so it is skipped, and index 3 finds nothing.

    Step by step

    1. Sort a copy. nums.sorted() goes into a let that is also named nums. Parameters are constants in Swift and can't be sorted in place, and the new nums hides the parameter for the rest of the method.
    2. Store the length in n.
    3. Create result, an empty [[Int]]. Each element will be one triplet.
    4. Loop over the first number with i over 0..<n - 2. The other two numbers sit to its right, so i stops two places before the end.
    5. Skip repeated first numbers. If i > 0 and nums[i] equals nums[i - 1], continue. The same first number would find the same triplets again.
    6. Place the pointers: left at i + 1 and right at 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. Too small: when total < 0, add 1 to left.
    10. Too large: when total > 0, subtract 1 from right.
    11. A match: otherwise, append [nums[i], nums[left], nums[right]] to result. Its values are already in ascending order, because i < left < right in a sorted array.
    12. Move both pointers inward. Keeping one in place would need the other to hold the same value, which gives the same triplet.
    13. Skip repeats of the second number. While left < right and nums[left] equals nums[left - 1], add 1 to left.
    14. Return result.

    The duplicate skip is only needed for left. After a match, a bigger value at left with the old value at right gives a positive total, and the branch for a positive total moves right by itself.

    The solution in Swift

    class Solution {
        func threeSum(_ nums: [Int]) -> [[Int]] {
            let nums = nums.sorted()
            let n = nums.count
            var result = [[Int]]()
            for i in 0..<n - 2 {
                if i > 0 && nums[i] == nums[i - 1] { continue }
                var left = i + 1, right = n - 1
                while left < right {
                    let total = nums[i] + nums[left] + nums[right]
                    if total < 0 {
                        left += 1
                    } else if total > 0 {
                        right -= 1
                    } else {
                        result.append([nums[i], nums[left], nums[right]])
                        left += 1
                        right -= 1
                        while left < right && nums[left] == nums[left - 1] {
                            left += 1
                        }
                    }
                }
            }
            return result
        }
    }
    

    Swift details worth knowing:

    • Shadowing. let nums = nums.sorted() declares a new constant with the same name as the parameter. The right side still refers to the parameter, and later lines see the sorted array. The caller's array is unchanged.
    • sorted() against sort(). sorted() returns a new sorted array, and sort() sorts in place, which needs a var.
    • Braces are required. if i > 0 && nums[i] == nums[i - 1] { continue } fits on one line, but Swift never allows an if body without braces.
    • 0..<n - 2 is a range up to n - 3. For n = 2 it is empty, but for fewer than two elements its end is below its start, which stops the program. The constraints promise at least 3 elements.
    • Two variables in one var. var left = i + 1, right = n - 1 declares both pointers on one line.
    • Nested array type. [[Int]]() is an empty array whose elements are arrays of Int.

    Complexity

    Time: O(n²). The sort costs O(n log n). The outer loop runs n - 2 times, and for each i the two pointers together move at most n steps, because every iteration of the inner loop moves at least one of them.

    Space: O(1) extra, apart from the sorted copy and the returned triplets. The method keeps a few integers.

    Edge cases and common mistakes

    • No triplet. [0, 1, 1] and [1, 2, 3] both return [].
    • All zeros. [0, 0, 0] and [0, 0, 0, 0] both return [[0, 0, 0]], once.
    • Repeated values. [-2, 0, 1, 1, 2] returns [[-2, 0, 2], [-2, 1, 1]]. A triplet may use the same value twice when the array holds it twice.
    • Skipping duplicates of i the wrong way. Comparing nums[i] with nums[i + 1] would skip the first copy and lose triplets like [-1, -1, 2]. The check looks back at nums[i - 1], so the first copy of each value always gets its turn.
    • Forgetting to sort. Both the pointer moves and the duplicate skipping depend on the order.
    • Forgetting to move the pointers after a match. The loop would find the same triplet forever.
    • Using a set of triplets. It also removes duplicates, but it costs extra memory and the answer would need sorting afterwards.

    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]].
    • [-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 Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free