Start learning free

LESSON 65 OF 321 · TWO POINTERS

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

Practice O(n2) Read the full explanation

You get a vector 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

    C++ · TWO POINTERS

    3sum in C++, explained

    Problem overview

    The method threeSum takes a vector<int> named nums and returns every triplet of values that adds up to 0, taken from three different indices. 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 themselves are in ascending order, comparing first values, then second, then third.

    For [-1, 0, 1, 2, -1, -4] the answer is [[-1, -1, 2], [-1, 0, 1]]. The value -1 appears twice, so -1, 0, 1 can be built in two ways, but it is listed once. For [0, 0, 0, 0] the answer is [[0, 0, 0]], and for [0, 1, 1] it is empty. The statement asks for O(n²) time and O(1) extra space, apart from sorting and the returned triplets.

    Approach: fix one number, then run two pointers

    Trying every triple of indices costs O(n³), which is far too slow for 3000 elements, and removing duplicates afterwards needs extra work. Sorting first fixes both problems.

    Once nums is sorted, fix the first number of the triplet at index i. The other two numbers must lie to its right and add up to -nums[i]. Searching for a pair with a given sum in a sorted range is the classic two-pointer job: start one pointer at each end of the range and compare the sum.

    • If the total is below 0, the sum is too small. The only way to raise it is to move left to a bigger value.
    • If the total is above 0, move right to a smaller value.
    • If the total is 0, record the triplet and move on.

    Each value of i costs O(n) for the pointer walk, so the whole thing is O(n²). The sort costs O(n log n), which is smaller.

    Sorting also makes duplicates easy to skip, because equal values sit next to each other. And since the scan goes left to right through a sorted vector, with i < left < right, every triplet is already in ascending order and the triplets come out in ascending order too. No final sort is needed.

    Step by step

    1. Sort nums with sort(nums.begin(), nums.end()).
    2. Store the length in an int named n.
    3. Create an empty vector<vector<int>> named result. Each element is one triplet.
    4. Loop over the first number with i from 0 while i < n - 2. The other two numbers sit to the right, so i stops two places before the end.
    5. Skip repeated first numbers. If i > 0 and nums[i] == nums[i - 1], continue. The same first value would find the same triplets again.
    6. Set the pointers: left = i + 1 and right = n - 1.
    7. Loop while left < right. When they meet, every pair for this i has been considered.
    8. Compute total as nums[i] + nums[left] + nums[right].
    9. Total below 0: left++.
    10. Total above 0: right--.
    11. Total equal to 0: push_back the braced list {nums[i], nums[left], nums[right]}.
    12. Move both pointers inward after a hit. Keeping one in place would need the other one's old value again, which gives the same triplet.
    13. Skip repeated second numbers: while left < right and nums[left] == nums[left - 1], do left++. There is no matching loop for right: if right still holds an old value, the total is now too big, and the "above 0" branch moves it.
    14. Return result after the loops.

    The solution in C++

    class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            sort(nums.begin(), nums.end());
            int n = nums.size();
            vector<vector<int>> result;
            for (int i = 0; i < n - 2; i++) {
                if (i > 0 && nums[i] == nums[i - 1]) continue;
                int left = i + 1, right = n - 1;
                while (left < right) {
                    int total = nums[i] + nums[left] + nums[right];
                    if (total < 0) {
                        left++;
                    } else if (total > 0) {
                        right--;
                    } else {
                        result.push_back({nums[i], nums[left], nums[right]});
                        left++;
                        right--;
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }
                    }
                }
            }
            return result;
        }
    };
    

    The C++ details worth knowing:

    • sort changes the caller's vector. nums is a reference, so after the call the caller's vector is sorted. That is fine for this problem, but it is a side effect. Pass the vector by value if you need to keep the original order.
    • n is an int on purpose. nums.size() is unsigned, so nums.size() - 2 would wrap to a huge number for a vector with fewer than two elements. Copying the size into an int keeps n - 2 an ordinary signed value. The constraints promise at least three elements, so the loop is safe here.
    • push_back({a, b, c}) builds a new vector<int> of three numbers from the braced list and adds it to result.
    • continue skips the rest of the loop body and moves to the next i. The short if (...) continue; on one line is legal when the body is a single statement.
    • The sum can't overflow. Values stay within plus or minus 100000, so the sum of three fits easily in an int.

    Tracing the example

    After sorting, [-1, 0, 1, 2, -1, -4] becomes [-4, -1, -1, 0, 1, 2]. These are the checks the loops make:

    ileftrighttotalAction
    015-3too small, move left
    025-3too small, move left
    035-2too small, move left
    045-1too small, move left, then the pointers meet
    1250record [-1, -1, 2]
    1340record [-1, 0, 1]
    2---skipped: nums[2] equals nums[1]
    3453too big, move right, then the pointers meet

    The loop over i ends there because i < n - 2 means i < 4. The result is [[-1, -1, 2], [-1, 0, 1]].

    Complexity

    Time is O(n²). Sorting is O(n log n). For each i, left and right together move at most n steps, because each step moves one of them inward and they never move back.

    Extra space is O(1) apart from the sort's internal needs and the returned triplets, as the statement allows.

    Edge cases and common mistakes

    • All zeros. [0, 0, 0, 0] gives one triplet, [0, 0, 0]. After recording it, left and right move inward, the duplicate-skipping loop runs while left < right, and the pointers meet. Later values of i are skipped as repeats. Exactly three zeros give the same single triplet.
    • No answer. [0, 1, 1] returns an empty vector.
    • Repeated values inside a triplet. The example's [-1, -1, 2] uses the same value twice, from two different indices. That is allowed. The duplicate skipping only rejects a repeat of the same first value, or of the same second value after a hit.
    • Skipping duplicates by comparing with the next element. Checking nums[i] == nums[i + 1] instead of nums[i - 1] would skip the first copy of a value, and so lose triplets like [-1, -1, 2]. Compare with the previous element, so the first copy is processed and later copies are skipped.
    • Forgetting to move both pointers after a hit. If neither moves, the loop runs forever on the same total.
    • A bigger example. For [-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6] the answer is [[-4, -2, 6], [-4, 0, 4], [-4, 1, 3], [-4, 2, 2], [-2, -2, 4], [-2, 0, 2]]. Each triplet appears once, even though 6, 4, 3, 2 and -2 each repeat in the input.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free