Start learning free

LESSON 65 OF 314 · TWO POINTERS

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

    TYPESCRIPT · TWO POINTERS

    3sum in TypeScript, explained

    Problem overview

    The method threeSum receives an array of numbers, nums, and returns every triplet [nums[i], nums[j], nums[k]] that adds up to 0, where i, j and k are three different indices. A triplet made of the same three values counts once, whichever indices it comes from. Each triplet has its values in ascending order, and the triplets are in ascending order too, compared by first value, then second, then third. The algorithm should run in O(n²) time and use O(1) extra space, apart from sorting and the returned triplets.

    For nums = [-1, 0, 1, 2, -1, -4] the answer is [[-1, -1, 2], [-1, 0, 1]]. The value -1 appears twice, so the triplet [-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]].

    Approach: fix one number, then run two pointers

    Trying every triple of indices is O(n³), too slow for 3000 numbers, and it also needs a way to discard duplicate triplets. Sorting solves both problems.

    After sorting, fix the first number nums[i]. The other two must add up to -nums[i], and they lie to the right of i. That is the pair-sum problem on a sorted range, solved with two pointers: left starts just after i and right at the last index. Look at the sum of the three numbers:

    • If it is less than 0, it is too small. Only a bigger value at left can raise it, so move left right.
    • If it is greater than 0, move right left to get a smaller value.
    • If it is 0, record the triplet and move both pointers inward.

    Each fixed i costs O(n) for the pointer walk, and there are about n values of i, giving O(n²).

    Duplicates are also easy in a sorted array, because equal values sit side by side. Skipping a first number equal to the previous one, and skipping repeated second numbers after a hit, keeps every triplet unique. The triplets also come out in the required order: the first value never decreases with i, and for one i the second value only increases as left moves right.

    On [-1, 0, 1, 2, -1, -4], sorting gives [-4, -1, -1, 0, 1, 2]. With i at -4 no pair reaches 4. With i at the first -1, the pointers find [-1, -1, 2] and then [-1, 0, 1]. The second -1 is skipped because it equals its predecessor.

    Step by step

    1. Sort nums with sort((a, b) => a - b). Without a compare function, sort orders numbers as text, so [10, 9, 1, -1] becomes [-1, 1, 10, 9].
    2. Store the length in n.
    3. Create result as an empty number[][], one small array per triplet.
    4. Loop i while i < n - 2. The other two numbers need room to the right.
    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. Set the pointers: left is i + 1 and right is n - 1.
    7. Loop while left < right. When they meet, all pairs for this i have been checked.
    8. Add the three numbers into total.
    9. If total is below 0, move left up.
    10. Else if it is above 0, move right down.
    11. Otherwise it is 0: push [nums[i], nums[left], nums[right]]. The values are already ascending because i < left < right in a sorted array.
    12. Move both pointers inward. Moving only one would need the other's old value again and give the same triplet.
    13. Skip repeated second numbers: while left < right and nums[left] equals nums[left - 1], move left up. No matching loop is needed for right: with a bigger value at left, an old value at right makes the sum too large, and the positive-total branch moves it.
    14. Return result.

    The solution in TypeScript

    class Solution {
        threeSum(nums: number[]): number[][] {
            nums.sort((a, b) => a - b);
            const n = nums.length;
            const result: number[][] = [];
            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 TypeScript details:

    • The compare function. (a, b) => a - b returns a negative number when a belongs first, which gives ascending numeric order. Values here are at most 10^5 in size, so the subtraction is exact.
    • sort changes the array it is called on. After threeSum, the caller's nums is sorted. For [3, 1, 2] the caller sees [1, 2, 3] afterwards. Copy first with [...nums] if that matters.
    • Triplets are plain arrays. result.push([a, b, c]) adds a new array of three numbers, which is why result is typed number[][].
    • Single-line continue. An if without braces runs just the next statement, here the continue.

    Complexity

    Time: O(n²). Sorting is O(n log n). Then each i runs a pointer walk in which left and right together move at most n steps, and the duplicate-skipping loops only move left forward within the same walk.

    Space: O(1) beyond the output, apart from the space the sort uses and the triplets returned.

    Edge cases and common mistakes

    • Sorting without a compare function. Numbers are compared as text, so negative numbers and multi-digit numbers end up in the wrong order and the pointer logic breaks.
    • Forgetting to skip duplicates. For [0, 0, 0, 0] the result would contain [0, 0, 0] twice or more. With the skips, it appears once.
    • Skipping the wrong way. Comparing nums[i] with nums[i + 1] instead of nums[i - 1] would skip the first copy and lose triplets that use two equal values, such as [-1, -1, 2].
    • Exactly three zeros. [0, 0, 0] gives [[0, 0, 0]]. [0, 1, 1] gives [] because the only triplet adds up to 2.
    • No triplet. The method returns an empty array, not undefined.
    • Reusing an index. left starts at i + 1 and the loop ends when left < right fails, so no index appears twice in a triplet.

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