Start learning free

LESSON 347 OF 671 · TWO POINTERS

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

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

    JAVA · TWO POINTERS

    3sum in Java, explained

    Problem overview

    The method threeSum receives an int[] nums and returns a List<List<Integer>> of all triplets [nums[i], nums[j], nums[k]] that add up to 0, where i, j and k are three different indices. The answer must not contain the same triplet twice, whichever indices it came from. Each triplet is written in ascending order and the triplets are listed in ascending order as well.

    For [-1, 0, 1, 2, -1, -4] the answer is [[-1, -1, 2], [-1, 0, 1]]. Three different index choices give the values -1, 0, 1 or -1, -1, 2, but only two distinct triplets exist. For [0, 0, 0, 0] many index choices give 0 + 0 + 0, yet the answer is the single triplet [[0, 0, 0]]. For [0, 1, 1] the answer is the empty list.

    Approach: fix one number, then run two pointers

    The brute force tries every triple of indices: three nested loops, O(n³) time. With up to 3000 numbers that is billions of checks. It also needs extra work to throw away repeated triplets.

    Sorting nums first changes the problem in two ways:

    • Equal values sit side by side, so repeats are easy to skip.
    • For a fixed first number, the other two can be found with two pointers. Put left just after it and right at the end. If the sum is too small, only moving left right can raise it. If it is too large, only moving right left can lower it.

    The sort costs O(n log n), and the pointer scan for each first number costs O(n), so the total is O(n²). Since the array is scanned from left to right in sorted order, every triplet comes out with nums[i] <= nums[left] <= nums[right] and the triplets arrive already in the order the statement asks for, so no sort of the result is needed.

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

    ileftrighttotalAction
    015-3too small: left moves
    025-3too small: left moves
    035-2too small: left moves
    045-1too small: left moves, the pointers meet
    1250found [-1, -1, 2]
    1340found [-1, 0, 1]
    2---skipped: same value as index 1
    3453too large: right moves, the pointers meet

    Step by step

    1. Sort. Arrays.sort(nums) sorts the array in ascending order, in place.
    2. Store the length in n, and create the empty result list, a List<List<Integer>> holding a new ArrayList. Each element of it is itself a list of three numbers.
    3. Choose the first number. Loop i from 0 while i < n - 2. The other two numbers lie to the right of i, so it stops two places before the end.
    4. Skip repeated first numbers. If i > 0 and nums[i] == nums[i - 1], continue. The same first number would find the same triplets again.
    5. Place the pointers. left = i + 1 and right = n - 1.
    6. Loop while left < right. When they meet, every pair for this i has been checked.
    7. Compute total as nums[i] + nums[left] + nums[right].
    8. Too small or too large. If total < 0, do left++. If total > 0, do right--.
    9. Found one. Otherwise total is 0, so add the triplet with Arrays.asList(nums[i], nums[left], nums[right]). Its values are already ascending, because i < left < right in a sorted array.
    10. Move both pointers inward. Keeping one in place would need the other one's old value to reach 0 again, which gives the same triplet.
    11. Skip repeated second numbers. While left < right and nums[left] == nums[left - 1], do left++. No loop is needed for right: with a bigger value at left, an old value at right makes the total positive, and the total > 0 branch moves it.
    12. Return result.

    The solution in Java

    class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            Arrays.sort(nums);
            int n = nums.length;
            List<List<Integer>> result = new ArrayList<>();
            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(Arrays.asList(nums[i], nums[left], nums[right]));
                        left++;
                        right--;
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }
                    }
                }
            }
            return result;
        }
    }
    

    The Java details worth a closer look:

    • Arrays.sort changes the caller's array. The method sorts nums in place, so after the call, [-1, 0, 1, 2, -1, -4] reads [-4, -1, -1, 0, 1, 2]. That is acceptable here, since the method returns only the triplets. To keep the original order, sort a copy made with Arrays.copyOf.
    • Arrays.asList(a, b, c) and boxing. The three int values are autoboxed into Integer objects and wrapped in a fixed-size list. Calling add on one of those triplets throws UnsupportedOperationException. Reading, which is all the answer needs, works normally.
    • Several variables in one declaration. int left = i + 1, right = n - 1; declares both in one statement.
    • One-line if. if (i > 0 && nums[i] == nums[i - 1]) continue; works without braces. Because && short-circuits, nums[i - 1] is never read when i is 0.
    • Comparing values. nums[i] == nums[i - 1] compares int values, so == is correct. It would not be for two Integer objects, which should be compared with equals.
    • Overflow. The values stay within plus or minus 100,000, so the sum of three can never overflow an int.

    Complexity

    Time: O(n²). Sorting is O(n log n). For each of the at most n values of i, the pointers together move at most n steps, because each step moves one of them toward the other. That is O(n) per i and O(n²) overall, which dominates the sort.

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

    Edge cases and common mistakes

    • Nothing found. [0, 1, 1] and [1, 2, 3] give [], an empty list, not null.
    • All zeros. [0, 0, 0, 0] gives one triplet. The first number is used once, and the pointers then meet.
    • Forgetting to skip repeated first numbers. On [-1, -1, 0, 1, 2] the answer becomes [[-1, -1, 2], [-1, 0, 1], [-1, 0, 1]], with [-1, 0, 1] twice. With the skip, it is [[-1, -1, 2], [-1, 0, 1]].
    • Skipping the wrong way. Comparing nums[i] with nums[i + 1] instead of nums[i - 1] would drop triplets that use two equal values, such as [-1, -1, 2]. Comparing with the previous value skips only the repeats of a first number already tried.
    • Repeated values in the middle. [-2, 0, 0, 2, 2] gives [[-2, 0, 2]]: the two 0s and the two 2s would otherwise give the same triplet again.
    • Starting left at 0. The pointer must begin right after i. Otherwise a number could pair with itself or with an earlier first number, repeating combinations.

    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]].
    • [-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 Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free