Start learning free

LESSON 65 OF 314 · TWO POINTERS

3Sum in Rust: 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

    RUST · TWO POINTERS

    3sum in Rust, explained

    Problem overview

    The function three_sum receives a vector of integers, nums, and returns every triplet of values that adds up to 0, taken from three different positions. The answer must not repeat a triplet: three values count once however many index combinations produce them. Each triplet is written in ascending order, and the triplets are returned in ascending order too, comparing first values, then second values, then third values.

    For [-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]]: many index choices give 0 + 0 + 0, but they form one triplet. For [0, 1, 1] it is an empty vector. The limit is O(n²) time, ignoring the sort and the output.

    Approach: fix one number, then run two pointers

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

    • Equal values sit side by side, so duplicates can be skipped by comparing a value with its neighbour.
    • A sorted vector tells the pointers which way to move. Fix the first number at i. Put left just after it and right at the end. If the sum is too small, only a bigger value at left can raise it, so left moves right. If the sum is too large, right moves left. If it is 0, record the triplet and move both inward.

    Each value of i costs one pass of the two pointers, O(n), so the whole scan is O(n²). Because the vector is sorted and i < left < right, each triplet is already in ascending order, and scanning left to right produces the triplets in ascending order as well, so no final sort is needed.

    Here is the scan on [-1, 0, 1, 2, -1, -4]. The sorted vector is [-4, -1, -1, 0, 1, 2], and the steps are:

    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
    

    With i = 0 (value -4) the sums are always too small, so left moves until the pointers meet. With i = 1 (value -1) the first sum is -1 + -1 + 2 = 0, which gives [-1, -1, 2], and then -1 + 0 + 1 = 0 gives [-1, 0, 1]. At i = 2 the value -1 repeats the previous one, so it is skipped.

    Step by step

    1. Sort nums. The parameter is immutable, so bind it again with let mut nums = nums; and call sort(), which sorts in place.
    2. Store the length in n, used for the loop bounds.
    3. Create result as an empty Vec<Vec<i32>>. Each element will be one triplet.
    4. Loop over the first number with i going over 0..n - 2, because two more values must follow it.
    5. Skip a repeated first number: if i > 0 and nums[i] equals nums[i - 1], continue. The same first value would find the same triplets again.
    6. Set the pointers: left at i + 1 and right at n - 1, both mutable.
    7. Loop while left < right. When they meet, every pair for this i has been tried.
    8. Compute total as nums[i] + nums[left] + nums[right].
    9. Total below 0: add 1 to left.
    10. Total above 0: subtract 1 from right.
    11. Otherwise the total is 0: push vec![nums[i], nums[left], nums[right]] onto result.
    12. Move both pointers inward. Keeping one in place would need the other one's old value again, and that repeats the triplet.
    13. Skip repeats of the second number: while left < right and nums[left] equals nums[left - 1], ...
    14. ...add 1 to left.
    15. Return result as the last expression.

    The solution in Rust

    impl Solution {
        fn three_sum(nums: Vec<i32>) -> Vec<Vec<i32>> {
            let mut nums = nums;
            nums.sort();
            let n = nums.len();
            let mut result: Vec<Vec<i32>> = Vec::new();
            for i in 0..n - 2 {
                if i > 0 && nums[i] == nums[i - 1] {
                    continue;
                }
                let mut left = i + 1;
                let mut 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.push(vec![nums[i], nums[left], nums[right]]);
                        left += 1;
                        right -= 1;
                        while left < right && nums[left] == nums[left - 1] {
                            left += 1;
                        }
                    }
                }
            }
            result
        }
    }
    

    The Rust details worth a closer look:

    • Shadowing to get mutability. let mut nums = nums; moves the vector into a new mutable binding with the same name. The alternative is to declare the parameter as mut nums in the signature, but the lesson keeps the signature as given.
    • usize arithmetic. n - 2 would underflow for fewer than two elements, and right -= 1 would underflow if right were 0. The first can't happen because the constraints guarantee at least 3 numbers. The second can't happen because the loop only runs while left < right, so right is at least 1.
    • The range 0..n - 2 excludes its end, so i stops at n - 3, the last index that still has two values after it.
    • vec![a, b, c] builds a vector from its elements, and push moves it into result.
    • Sum overflow. The values are at most 100,000 in absolute value, so a sum of three is far below the i32 limit.
    • Why only left skips duplicates. After a match, a repeated value at left would pair with the same right and rebuild the same triplet, so the loop steps past it. A repeated value at right needs no loop: next to the bigger left, it makes the total positive, and the positive-total branch moves right by itself.

    Complexity

    Time: O(n²). Sorting costs O(n log n). For each i, left only moves right and right only moves left, so the pointer loop makes at most n steps. With up to n values of i, that is O(n²), which dominates the sort.

    Space: O(1) beyond the sort and the output. The code uses a few integers, and the triplets it returns are the answer itself. The sort is done in place on the vector the function owns.

    Edge cases and common mistakes

    • All zeros. [0, 0, 0, 0] gives [[0, 0, 0]], one triplet, although four positions can be chosen three at a time in several ways. The skip of a repeated i is what keeps the later zeros from adding the triplet again.
    • Repeated values that still form one triplet. [-2, 0, 0, 2, 2] gives [[-2, 0, 2]], even though the 0s and 2s can be chosen in several ways. After the first match, the skip of the repeated 0 at left stops the second 0 and 2 from recording it again.
    • No answer. [0, 1, 1] gives [].
    • Three values only. [3, -1, -2] gives [[-2, -1, 3]]: the triplet is written in ascending order, not in the input order.
    • Using the same position twice. The pointers satisfy i < left < right, so a position is never used twice, while two equal values at different positions are fine, as in [-1, -1, 2].
    • Forgetting the skip of a repeated i. The two -1 values in the first example would each start a scan and the triplet [-1, 0, 1] would appear twice.

    Testing

    • nums = [-1, 0, 1, 2, -1, -4] gives [[-1, -1, 2], [-1, 0, 1]].
    • nums = [0, 1, 1] gives [].
    • nums = [0, 0, 0, 0] gives [[0, 0, 0]].
    • nums = [-2, 0, 0, 2, 2] gives [[-2, 0, 2]].
    • nums = [-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 Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free