Start learning free

LESSON 347 OF 671 · TWO POINTERS

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

    JAVASCRIPT · TWO POINTERS

    3sum in JavaScript, explained

    Problem overview

    The method threeSum(nums) receives an array of integers and returns every triplet of values [nums[i], nums[j], nums[k]] that adds up to 0, using three different indices. The answer must not contain the same triplet twice: three values count once, whichever indices they come from. Each triplet is written in ascending order, and the triplets are listed in ascending order too, compared by first value, then second, then third.

    For [-1, 0, 1, 2, -1, -4] the answer is [[-1, -1, 2], [-1, 0, 1]]. Several index choices give [-1, 0, 1], but it is listed once. For [0, 0, 0, 0] the answer is [[0, 0, 0]], and for [0, 1, 1] it is [].

    Approach: fix one number, then walk two pointers

    Trying every triple of indices costs O(n³), and removing duplicates afterwards needs extra work. The statement asks for O(n²), which comes from sorting first and then handling the problem as a series of two-number searches.

    1. Sort nums in ascending order. Equal values end up side by side, so repeats are easy to skip, and the sums behave predictably.
    2. Fix the first number nums[i]. The other two must come from the part of the array to its right.
    3. Search that part with two pointers: left starts just after i and right at the last index. Add the three values:
      • if the total is below 0, move left right: in a sorted array that is the only way to make the sum bigger;
      • if the total is above 0, move right left to make it smaller;
      • if the total is 0, record the triplet and move both pointers inward.

    Each pointer only moves in one direction, so the scan for one i takes O(n), and n values of i give O(n²). Because the array is sorted and the loop goes from left to right, every triplet comes out in ascending order, with its three values ascending too (i < left < right). The answer needs no sorting at the end.

    Duplicates are removed in two places. A first number equal to the previous one is skipped, since it would find the same triplets again. After a hit, left advances past values equal to the one just used. The right pointer needs no such loop: once left has moved to a larger value, a repeated value at right makes the total positive, and the existing branch moves it.

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

    ileftrighttotalaction
    015-3move left
    025-3move left
    035-2move left
    045-1move left; the pointers meet
    1250record [-1, -1, 2]
    1340record [-1, 0, 1]
    2skipped: same value as index 1
    3453move right; the pointers meet

    Step by step

    1. Sort nums with the comparator (a, b) => a - b. Without a comparator, sort compares numbers as text.
    2. Store the length in n, used by the loop bounds.
    3. Create an empty result to collect triplets in the order they are found.
    4. Loop over the first number with i < n - 2, because two more values must fit to its right.
    5. Skip repeated first numbers with continue when i > 0 and nums[i] === nums[i - 1].
    6. Set the pointers: left = i + 1 and right = n - 1.
    7. Loop while left < right. When they meet, all pairs for this i are checked.
    8. Add the three numbers into total.
    9. Total below 0: increment left.
    10. Total above 0: decrement right.
    11. Total equal to 0: push [nums[i], nums[left], nums[right]].
    12. Move both pointers inward. Keeping one in place would need the other's value again, which gives the same triplet.
    13. Skip equal second numbers with an inner while that increments left while nums[left] === nums[left - 1].
    14. Return result.

    The solution in JavaScript

    class Solution {
        threeSum(nums) {
            nums.sort((a, b) => a - b);
            const n = nums.length;
            const result = [];
            for (let i = 0; i < n - 2; i++) {
                if (i > 0 && nums[i] === nums[i - 1]) continue;
                let left = i + 1, right = n - 1;
                while (left < right) {
                    const total = nums[i] + nums[left] + nums[right];
                    if (total < 0) {
                        left++;
                    } else if (total > 0) {
                        right--;
                    } else {
                        result.push([nums[i], nums[left], nums[right]]);
                        left++;
                        right--;
                        while (left < right && nums[left] === nums[left - 1]) {
                            left++;
                        }
                    }
                }
            }
            return result;
        }
    }
    

    Some JavaScript details worth knowing:

    • The comparator matters. [10, 9, 1, -5, -12].sort() gives [-12, -5, 1, 10, 9], because the numbers are compared as strings. With (a, b) => a - b it gives [-12, -5, 1, 9, 10]. The subtraction is safe here, since the values stay within plus or minus 100,000.
    • sort changes the array it is called on. After threeSum([3, -1, -2, 10, -10, 0]) the caller's array reads [-10, -2, -1, 0, 3, 10]. If the caller needs the original order, sort a copy with [...nums].sort(...).
    • === for comparing values. Numbers are compared by value, so nums[i] === nums[i - 1] detects a repeat.
    • One-line if with continue. continue skips the rest of the loop body and goes on to the next i, so no braces are needed for a single statement.
    • Triplets are new arrays. Every push([...]) creates a fresh three-element array, so the entries of result don't share anything.

    Complexity

    Time: O(n²). Sorting costs O(n log n). The outer loop runs about n times, and for each i the two pointers together move at most n steps. The quadratic part dominates.

    Space: O(1) extra, apart from the sort's own working space and the triplets returned. The function keeps only a handful of variables.

    Edge cases and common mistakes

    • Comparing with the next element instead of the previous one. The check for a repeated first number looks back, at nums[i - 1], so the first copy of a value is always tried.
    • Forgetting the comparator. A default sort() orders numbers as text, which breaks the two-pointer logic as soon as the values have different numbers of digits or signs.
    • All zeros. [0, 0, 0, 0] gives one triplet, [[0, 0, 0]]. After the first hit, left and right move inward and meet, and later values of i are skipped as repeats.
    • Exactly three elements. [1, 2, -3] gives [[-3, 1, 2]], and [0, 0, 0] gives [[0, 0, 0]]. With fewer than three, the loop bound n - 2 would never allow an iteration.
    • Repeated values in one triplet. [-2, 0, 1, 1, 2] gives [[-2, 0, 2], [-2, 1, 1]]. Repeats are skipped only for the first number of a new i and after a hit, so [-2, 1, 1] is still found.
    • No triplet. [0, 1, 1] returns [], an empty array.

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