Start learning free

LESSON 65 OF 314 · TWO POINTERS

3Sum in Kotlin: O(n^2) 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

    KOTLIN · TWO POINTERS

    3sum in Kotlin, explained

    Problem overview

    The function threeSum receives an IntArray named nums and returns a List<IntArray> holding every triplet of values that add up to 0. The three values must come from three different indices, and the answer must not repeat a triplet: the same three values count once, whichever indices they come from. Each triplet is written in ascending order, and the triplets are in ascending order too, comparing first values, then second, then third.

    For [-1, 0, 1, 2, -1, -4] the answer is [[-1,-1,2],[-1,0,1]]. The value -1 appears twice in the input, so the triplet [-1, 0, 1] can be built from either one, but it is reported once. For [0, 1, 1] the answer is empty, and for [0, 0, 0, 0] it is [[0,0,0]], because the many ways to pick three zeros form one triplet.

    Approach

    The brute force tries every set of three indices, which takes O(n^3) time and still needs a way to drop repeated triplets. With up to 3000 numbers, that is far too slow.

    Sorting changes the problem. After sorting, fix the first value nums[i] and look for two values to its right that sum to -nums[i]. That is a two-pointer search: left starts just after i and right at the end of the array.

    • If the total is below 0, only a bigger value at left can raise it, so move left right.
    • If the total is above 0, a smaller value at right lowers it, so move right left.
    • If the total is 0, record the triplet and move both pointers inward.

    Each value of i costs one sweep of the pointers, O(n), so the whole search is O(n^2). Sorting adds O(n log n), which doesn't change the total. Sorting also puts equal values side by side, which makes skipping repeats easy, and it makes the triplets come out in the required order without a final sort.

    Step by step

    1. Sort. nums.sort() sorts the array in ascending order, in place.
    2. Store the length in val n = nums.size.
    3. Create the output list. mutableListOf<IntArray>() grows as triplets are found. Because nums is sorted and scanned from left to right, the triplets arrive in ascending order.
    4. Fix the first value. Loop i over 0 until n - 2. The other two values lie to the right of i, so it stops two places before the end.
    5. Skip repeated first values. If i > 0 and nums[i] == nums[i - 1], use continue. The same first value would find the same triplets again.
    6. Set the pointers. left is i + 1 and right is n - 1, both vars.
    7. Sweep. Loop while (left < right). When the pointers meet, every pair for this i has been checked.
    8. Add three numbers into val total.
    9. Too small: left++.
    10. Too large: right--.
    11. Exactly 0: add intArrayOf(nums[i], nums[left], nums[right]) to result. Its values are already ascending, because i < left < right in a sorted array.
    12. Move both pointers inward with left++ and right--. Moving only one would need the other's value again and give the same triplet.
    13. Skip repeated second values. While left < right and nums[left] == nums[left - 1], increment left. The same second value would build the same triplet again. right needs no such loop: with a bigger value at left, an old value at right makes the total too large, and the branch for a positive total moves it.
    14. Return result.

    On the sorted input [-4, -1, -1, 0, 1, 2], the pointer positions and totals go as follows:

    i=0 l=1 r=5 total=-3
    i=0 l=2 r=5 total=-3
    i=0 l=3 r=5 total=-2
    i=0 l=4 r=5 total=-1
    i=1 l=2 r=5 total=0
    i=1 l=3 r=4 total=0
    i=2 skipped
    i=3 l=4 r=5 total=3
    

    The two zero totals at i=1 give [-1,-1,2] and [-1,0,1]. At i=2 the value equals the one before it, so the whole sweep is skipped.

    The solution in Kotlin

    class Solution {
        fun threeSum(nums: IntArray): List<IntArray> {
            nums.sort()
            val n = nums.size
            val result = mutableListOf<IntArray>()
            for (i in 0 until n - 2) {
                if (i > 0 && nums[i] == nums[i - 1]) continue
                var left = i + 1
                var right = n - 1
                while (left < right) {
                    val total = nums[i] + nums[left] + nums[right]
                    if (total < 0) {
                        left++
                    } else if (total > 0) {
                        right--
                    } else {
                        result.add(intArrayOf(nums[i], nums[left], nums[right]))
                        left++
                        right--
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++
                        }
                    }
                }
            }
            return result
        }
    }
    

    Kotlin details worth knowing:

    • sort() works in place. On an IntArray, nums.sort() reorders the caller's array. After calling the function on [-1, 0, 1, 2, -1, -4], that array reads [-4, -1, -1, 0, 1, 2]. sorted() would return a new list instead.
    • Arrays print badly. A List<IntArray> printed directly shows type tags like [I@ followed by hash digits, not the numbers. To see the triplets, convert each one with contentToString().
    • continue in a for loop skips the rest of the body and goes on with the next i. It is written on one line here because the body is one statement.
    • 0 until n - 2 excludes n - 2, so the last i is n - 3. With exactly three numbers, the loop runs once.
    • No overflow. Values stay within 10^5 in absolute value, so a sum of three fits easily in an Int.

    Complexity

    Time is O(n^2): sorting takes O(n log n), and the pointers sweep the array at most once for each of the n values of i. Extra space is O(1) apart from the sort and the returned triplets.

    Edge cases and common mistakes

    • Forgetting to skip repeated first values. Without the continue line, the input [-1, 0, 1, 2, -1, -4] returns [[-1,-1,2],[-1,0,1],[-1,0,1]], with [-1,0,1] twice.
    • Forgetting to skip repeated second values. Without the inner loop, [-2, 0, 0, 2, 2] returns [[-2,0,2],[-2,0,2]].
    • All zeros. [0, 0, 0, 0] gives [[0,0,0]]: one triplet, although there are four ways to choose the three indices.
    • No answer. [0, 1, 1] gives an empty list.
    • Comparing with nums[i + 1] instead of nums[i - 1]. Looking forward would skip the first copy of a value and miss triplets that use two equal values, such as [-1, -1, 2]. The checks compare with the previous element, so the first copy is always used.
    • Not sorting first. The pointer moves are only correct on sorted data.

    Testing

    Results the solution returns:

    [-1, 0, 1, 2, -1, -4] -> [[-1,-1,2],[-1,0,1]]
    [0, 1, 1]             -> []
    [0, 0, 0, 0]          -> [[0,0,0]]
    [-2, 0, 0, 2, 2]      -> [[-2,0,2]]
    
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free