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:
- Fix the first number,
nums(i). The other two must add up to-nums(i). - Look for those two numbers to the right of
iwith two pointers,leftat the start of that part andrightat the end. - If the three-number sum is too small, move
leftright to get a bigger number. If it is too big, moverightleft 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
- Sort
numsin place withscala.util.Sorting.quickSort(nums). - Store the length in
val n. - Create
result, anArrayBuffer[Array[Int]]. It grows as triplets are found; each element is one three-number array. - Loop over the first number with
i <- 0 until n - 2. The other two numbers sit to the right ofi, soistops two places before the end. - 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 nocontinue, so the rest of the loop's work sits inside thisif. - Set the pointers.
leftstarts ati + 1andrightatn - 1, bothvars. - Loop while
left < right. When the pointers meet, every pair for thisihas been checked. - Compute
totalasnums(i) + nums(left) + nums(right). - Total below 0: add 1 to
left. In a sorted array a bigger value atleftis the only way to raise the sum whileistays. - Total above 0: subtract 1 from
right, which lowers the sum. - Total equal to 0: append
Array(nums(i), nums(left), nums(right))toresultwith+=. The values are already ascending, becausei < left < rightin a sorted array. - Move both pointers inward. Keeping one in place would need the other one's old value again, which gives the same triplet.
- Skip equal second numbers. While
left < rightandnums(left) == nums(left - 1), add 1 toleft. A repeated second number would build the same triplet. No such loop is needed forright: if the newleftvalue is bigger, an unchangedrightvalue makes the sum positive, and the branch for a positive total moves it. - Return
result.toArray. The method returns anArray, 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:
quickSortsorts in place. It changes the array the caller passed in and returns nothing. After the call onArray(-1, 0, 1, 2, -1, -4),numsreads-4, -1, -1, 0, 1, 2. By contrast,nums.sortedreturns a new array and leavesnumsalone.ArrayBufferneeds an import. It comes fromscala.collection.mutable, so a standalone file needsimport scala.collection.mutable.ArrayBuffer.+=adds one element.result += Array(...)appends the whole three-number array as one entry.- Printing an array.
printlnof anArrayshows an identity string such as[I@..., not its contents. UsemkStringto see the numbers. - Everything is an expression. The
if/else if/elsechain here is used only for its effects, so its branches can be statements. The method's own value is the finalresult.toArray. Intsums 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]], andArray(1, 2, 3)gives an empty array. The outer loop runs once, fori = 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. ForArray(-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
iup ton. 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[].
