Start learning free

LESSON 65 OF 314 · TWO POINTERS

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

    SCALA · TWO POINTERS

    3sum in Scala, explained

    Problem overview

    The method threeSum takes an Array[Int] named nums and returns every triplet of values, taken from three different indices, that adds up to 0. The answer is an Array[Array[Int]]. 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 Array(-1, 0, 1, 2, -1, -4) the answer is [[-1,-1,2],[-1,0,1]]. For Array(0, 1, 1) it is empty, since the only triplet sums to 2. For Array(0, 0, 0, 0) it is [[0,0,0]]: several choices of three indices exist, but they all give the same triplet.

    Approach: fix one number, then squeeze two pointers

    Trying every triple of indices takes O(n³) time, and then the duplicates would still have to be removed. Sorting nums first allows something much better:

    1. Fix the first number, nums(i). The other two must add up to -nums(i).
    2. Look for those two numbers to the right of i with two pointers, left at the start of that part and right at the end.
    3. If the three-number sum is too small, move left right to get a bigger number. If it is too big, move right left to get a smaller one. If it is zero, record the triplet.

    Each fixed i costs one sweep of the two pointers, O(n), so the whole thing is O(n²) after the O(n log n) sort.

    Sorting also makes the duplicates easy to handle, because equal values sit side by side. And because the array is sorted and scanned from left to right, the triplets are found already in the order the problem asks for, each with ascending values, so no final sort is needed.

    Step by step

    1. Sort nums in place with scala.util.Sorting.quickSort(nums).
    2. Store the length in val n.
    3. Create result, an ArrayBuffer[Array[Int]]. It grows as triplets are found; each element is one three-number array.
    4. Loop over the first number with i <- 0 until n - 2. The other two numbers sit to the right of i, so i stops two places before the end.
    5. Skip repeated first numbers. The body runs only if i == 0 || nums(i) != nums(i - 1). The same first number would find the same triplets again. Scala has no continue, so the rest of the loop's work sits inside this if.
    6. Set the pointers. left starts at i + 1 and right at n - 1, both vars.
    7. Loop while left < right. When the pointers meet, every pair for this i has been checked.
    8. Compute total as nums(i) + nums(left) + nums(right).
    9. Total below 0: add 1 to left. In a sorted array a bigger value at left is the only way to raise the sum while i stays.
    10. Total above 0: subtract 1 from right, which lowers the sum.
    11. Total equal to 0: append Array(nums(i), nums(left), nums(right)) to result with +=. The values are already ascending, because i < left < right in a sorted array.
    12. Move both pointers inward. Keeping one in place would need the other one's old value again, which gives the same triplet.
    13. Skip equal second numbers. While left < right and nums(left) == nums(left - 1), add 1 to left. A repeated second number would build the same triplet. No such loop is needed for right: if the new left value is bigger, an unchanged right value makes the sum positive, and the branch for a positive total moves it.
    14. Return result.toArray. The method returns an Array, and the last expression of the method is its value.

    The solution in Scala

    class Solution {
        def threeSum(nums: Array[Int]): Array[Array[Int]] = {
            scala.util.Sorting.quickSort(nums)
            val n = nums.length
            val result = ArrayBuffer[Array[Int]]()
            for (i <- 0 until n - 2) {
                if (i == 0 || nums(i) != nums(i - 1)) {
                    var left = i + 1
                    var right = n - 1
                    while (left < right) {
                        val total = nums(i) + nums(left) + nums(right)
                        if (total < 0) {
                            left += 1
                        } else if (total > 0) {
                            right -= 1
                        } else {
                            result += Array(nums(i), nums(left), nums(right))
                            left += 1
                            right -= 1
                            while (left < right && nums(left) == nums(left - 1)) {
                                left += 1
                            }
                        }
                    }
                }
            }
            result.toArray
        }
    }
    

    Scala details worth knowing:

    • quickSort sorts in place. It changes the array the caller passed in and returns nothing. After the call on Array(-1, 0, 1, 2, -1, -4), nums reads -4, -1, -1, 0, 1, 2. By contrast, nums.sorted returns a new array and leaves nums alone.
    • ArrayBuffer needs an import. It comes from scala.collection.mutable, so a standalone file needs import scala.collection.mutable.ArrayBuffer.
    • += adds one element. result += Array(...) appends the whole three-number array as one entry.
    • Printing an array. println of an Array shows an identity string such as [I@..., not its contents. Use mkString to see the numbers.
    • Everything is an expression. The if / else if / else chain here is used only for its effects, so its branches can be statements. The method's own value is the final result.toArray.
    • Int sums can't overflow here. The values stay within plus or minus 100,000, so a sum of three is far below the 32-bit limit.

    Complexity

    Time: O(n²). Sorting costs O(n log n). For each i, the two pointers together move at most n steps, because each step moves one of them toward the other, and the duplicate-skipping loops move them in the same direction. That is O(n) per i and O(n²) overall.

    Space: O(1) extra, apart from sorting and the returned triplets. The method keeps a few integer variables; the buffer only holds the answer.

    Edge cases and common mistakes

    • Exactly three numbers. Array(0, 0, 0) gives [[0,0,0]], and Array(1, 2, 3) gives an empty array. The outer loop runs once, for i = 0.
    • Many equal values. Array(0, 0, 0, 0) gives one triplet, not four. After the first match, the pointers move inward and the skipping loop jumps over the equal values.
    • A triplet that repeats a value. Array(-2, 0, 1, 1, 2) gives [[-2,0,2],[-2,1,1]]. The two 1s are different indices, which the problem allows, and the triplet [-2,1,1] appears once.
    • Skipping the duplicate check on i. For Array(-1, -1, 0, 1)-style inputs, both -1s would find [-1,0,1] and the answer would repeat it.
    • Skipping the check on left. Without it, equal second numbers after a match produce repeated triplets.
    • Skipping the pointer moves after a match. The loop would find the same triplet forever.
    • Forgetting that sorting changes the input. The method reorders the caller's array. That is fine for the lesson, but a caller that needs the original order must copy first.
    • Looping i up to n. With fewer than two numbers to the right, the pointers would start crossed, and the loop would only do wasted work.

    Testing

    • Array(-1, 0, 1, 2, -1, -4) gives [[-1,-1,2],[-1,0,1]].
    • Array(0, 1, 1) gives [].
    • Array(0, 0, 0, 0) gives [[0,0,0]].
    • Array(0, 0, 0) gives [[0,0,0]].
    • Array(-2, 0, 1, 1, 2) gives [[-2,0,2],[-2,1,1]].
    • Array(1, 2, 3) gives [].
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free