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
leftcan raise it, so moveleftright. - If the total is above 0, a smaller value at
rightlowers it, so moverightleft. - 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
- Sort.
nums.sort()sorts the array in ascending order, in place. - Store the length in
val n = nums.size. - Create the output list.
mutableListOf<IntArray>()grows as triplets are found. Becausenumsis sorted and scanned from left to right, the triplets arrive in ascending order. - Fix the first value. Loop
iover0 until n - 2. The other two values lie to the right ofi, so it stops two places before the end. - Skip repeated first values. If
i > 0andnums[i] == nums[i - 1], usecontinue. The same first value would find the same triplets again. - Set the pointers.
leftisi + 1andrightisn - 1, bothvars. - Sweep. Loop
while (left < right). When the pointers meet, every pair for thisihas been checked. - Add three numbers into
val total. - Too small:
left++. - Too large:
right--. - Exactly 0: add
intArrayOf(nums[i], nums[left], nums[right])toresult. Its values are already ascending, becausei < left < rightin a sorted array. - Move both pointers inward with
left++andright--. Moving only one would need the other's value again and give the same triplet. - Skip repeated second values. While
left < rightandnums[left] == nums[left - 1], incrementleft. The same second value would build the same triplet again.rightneeds no such loop: with a bigger value atleft, an old value atrightmakes the total too large, and the branch for a positive total moves it. - 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 anIntArray,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 withcontentToString(). continuein aforloop skips the rest of the body and goes on with the nexti. It is written on one line here because the body is one statement.0 until n - 2excludesn - 2, so the lastiisn - 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
continueline, 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 ofnums[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]]
