Start learning free

LESSON 65 OF 314 · TWO POINTERS

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

    C# · TWO POINTERS

    3sum in C#, explained

    Problem overview

    The method ThreeSum receives an int[] called nums and returns a List<int[]> of all triplets of values that add up to 0. The three values must come from three different indices, and 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, comparing first values, then second, then third.

    For {-1, 0, 1, 2, -1, -4} the answer is [[-1, -1, 2], [-1, 0, 1]]. For {0, 1, 1} it is empty, and for {0, 0, 0, 0} it is the single triplet [0, 0, 0]. The method should run in O(n²) time.

    Approach: fix one number, scan for the other two

    Trying every triple of indices is O(n³), too slow for 3,000 elements. Using a set to remove duplicate triplets afterwards adds clumsy bookkeeping. The lesson uses a tidier idea built on sorting.

    After sorting nums, fix the first number nums[i]. The remaining two numbers must sum to -nums[i] and lie to the right of i. Because that part of the array is sorted, two pointers can find all such pairs in one sweep: left starts just after i and right at the last index. The sum of the three values tells which pointer to move:

    • A sum below 0 is too small. Only a larger value at left can raise it, so move left right.
    • A sum above 0 is too large. Move right left to get a smaller value.
    • A sum of 0 is a triplet: record it, then move both pointers inward.

    One sweep is O(n) and there are n choices of i, so the total is O(n²) after the O(n log n) sort.

    Sorting also makes duplicates easy to remove. Equal values sit side by side, so skipping a first number equal to the previous one and a second number equal to the previous one produces each distinct triplet once. And since i < left < right in a sorted array, every triplet comes out already in ascending order, and the triplets appear in ascending order too, so no final sort is needed.

    Here is the sorted array {-4, -1, -1, 0, 1, 2} in action:

    ileftrightsum
    015-3
    025-3
    035-2
    045-1
    1250
    1340
    3453

    For i = 0 (value -4) no pair works. For i = 1 (value -1) the sums of 0 give the triplets [-1, -1, 2] and [-1, 0, 1]. Index 2 is skipped because it repeats the value -1, and i = 3 finds nothing.

    Step by step

    1. Sort nums with Array.Sort.
    2. Store the length as n for the loop bounds.
    3. Create the list result of int[], one array per triplet.
    4. Loop i while i < n - 2. The other two numbers need two places to the right of i.
    5. Skip a repeated first number: if i > 0 and nums[i] == nums[i - 1], continue. The same first number would find the same triplets again.
    6. Place the pointers: left = i + 1, right = n - 1.
    7. Loop while left < right. When they meet, every pair for this i has been checked.
    8. Add the three values into total.
    9. Too small: left++.
    10. Too large: right--.
    11. Exactly zero: add new int[] { nums[i], nums[left], nums[right] } to the result.
    12. Move both pointers inward. Moving only one would need the other's old value again and repeat the triplet.
    13. Skip equal second numbers: while left < right and nums[left] == nums[left - 1], left++. No similar loop is needed for right: with a bigger value at left, an unchanged right makes the sum too large, and the "too large" branch moves it.
    14. Return result.

    The solution in C#

    class Solution {
        public List<int[]> ThreeSum(int[] nums) {
            Array.Sort(nums);
            int n = nums.Length;
            List<int[]> result = new List<int[]>();
            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.Add(new int[] { nums[i], nums[left], nums[right] });
                        left++;
                        right--;
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }
                    }
                }
            }
            return result;
        }
    }
    

    C# details worth knowing:

    • Array.Sort sorts in place. It reorders the caller's array and returns nothing. After the call on {-1, 0, 1, 2, -1, -4}, the caller's array reads {-4, -1, -1, 0, 1, 2}. Copy the array first if you need the original order.
    • List<int[]> is a growable list whose elements are arrays. new int[] { a, b, c } creates a three-element array in one expression. List needs using System.Collections.Generic; and Array needs using System; in a standalone file.
    • Sums stay in range. Values are within plus or minus 100,000, so adding three of them fits easily in an int. With values near int.MaxValue the sum could wrap silently, and a long would be needed.
    • continue on one line. An if without braces controls only the next statement, which is fine for a single continue.

    Complexity

    Time: O(n²). Sorting costs O(n log n). Each value of i then runs a two-pointer sweep in which left and right together move at most n steps.

    Space: O(1) extra, apart from the sort's own working space and the returned triplets.

    Edge cases and common mistakes

    • All zeros. {0, 0, 0, 0} returns one triplet, [0, 0, 0]. The duplicate skips stop the other index choices from adding it again.
    • Exactly three elements. {0, 0, 0} gives [[0, 0, 0]]: i = 0 is the only first number.
    • No answer. {0, 1, 1} gives an empty list.
    • Repeated values in a triplet. {-2, 0, 1, 1, 2} gives [[-2, 0, 2], [-2, 1, 1]]. The repeated 1 is allowed within a triplet, only a repeated triplet is not.
    • Skipping duplicates too early. Comparing nums[i] with nums[i + 1] would throw away a valid triplet such as [-1, -1, 2]. Comparing with the previous element lets the first copy be used.
    • Not sorting first. The pointer moves rely on order, and without it the duplicate skipping does not work.

    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]].
    • {0, 0, 0} gives [[0, 0, 0]].
    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