Problem overview
The method threeSum receives an array of integers, nums, and returns every triplet of values that adds up to 0, using three different indices. The answer must not contain the same triplet twice, however many index choices produce it. Each triplet is written in ascending order, and the triplets themselves are in ascending order too, comparing first values, then second, then third. The statement asks for O(n²) time and O(1) extra space, not counting the sort and the returned triplets.
For [-1, 0, 1, 2, -1, -4] the answer is [[-1, -1, 2], [-1, 0, 1]]. Several index choices give [-1, 0, 1], since the array holds two -1s, but it appears once. For [0, 0, 0, 0] the answer is [[0, 0, 0]].
Approach: fix one number, then squeeze two pointers
Trying every triple of indices takes O(n³), and removing duplicates would need extra bookkeeping. Sorting first changes the problem in two ways.
- Equal values sit side by side, so repeats are easy to skip.
- For a fixed first number, finding the other two becomes a search for a pair with a given sum in a sorted range, which two pointers do in one pass.
For each first number nums[i], one pointer left starts right after i and another, right, at the last index. Their sum with nums[i] is total:
- If
totalis below 0, the sum is too small, and the only way to raise it is a bigger value atleft, soleftmoves right. - If it is above 0,
rightmoves left to lower it. - If it is 0, record the triplet and move both pointers inward.
Each pointer only moves one way, so one first number costs O(n), and the whole method costs O(n²). Because the array is sorted and the scan goes left to right, the triplets are found already in the order the statement asks for, so no final sort is needed.
Here is the scan on the sorted array [-4, -1, -1, 0, 1, 2]:
i=0 left=1 right=5 total=-3
i=0 left=2 right=5 total=-3
i=0 left=3 right=5 total=-2
i=0 left=4 right=5 total=-1
i=1 left=2 right=5 total=0
i=1 left=3 right=4 total=0
i=2 skipped
i=3 left=4 right=5 total=3
For i = 0 the sum never reaches 0, so nothing is found. For i = 1 both lines with total 0 are triplets: [-1, -1, 2] and [-1, 0, 1]. Index 2 holds -1 again, so it is skipped, and index 3 finds nothing.
Step by step
- Sort a copy.
nums.sorted()goes into aletthat is also namednums. Parameters are constants in Swift and can't be sorted in place, and the newnumshides the parameter for the rest of the method. - Store the length in
n. - Create
result, an empty[[Int]]. Each element will be one triplet. - Loop over the first number with
iover0..<n - 2. The other two numbers sit to its right, soistops two places before the end. - Skip repeated first numbers. If
i > 0andnums[i]equalsnums[i - 1],continue. The same first number would find the same triplets again. - Place the pointers:
leftati + 1andrightatn - 1. - Loop while
left < right. When the pointers meet, every pair for thisihas been checked. - Compute
totalasnums[i] + nums[left] + nums[right]. - Too small: when
total < 0, add 1 toleft. - Too large: when
total > 0, subtract 1 fromright. - A match: otherwise, append
[nums[i], nums[left], nums[right]]toresult. Its values are already in ascending order, becausei < left < rightin a sorted array. - Move both pointers inward. Keeping one in place would need the other to hold the same value, which gives the same triplet.
- Skip repeats of the second number. While
left < rightandnums[left]equalsnums[left - 1], add 1 toleft. - Return
result.
The duplicate skip is only needed for left. After a match, a bigger value at left with the old value at right gives a positive total, and the branch for a positive total moves right by itself.
The solution in Swift
class Solution {
func threeSum(_ nums: [Int]) -> [[Int]] {
let nums = nums.sorted()
let n = nums.count
var result = [[Int]]()
for i in 0..<n - 2 {
if i > 0 && nums[i] == nums[i - 1] { continue }
var left = i + 1, right = n - 1
while left < right {
let total = nums[i] + nums[left] + nums[right]
if total < 0 {
left += 1
} else if total > 0 {
right -= 1
} else {
result.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while left < right && nums[left] == nums[left - 1] {
left += 1
}
}
}
}
return result
}
}
Swift details worth knowing:
- Shadowing.
let nums = nums.sorted()declares a new constant with the same name as the parameter. The right side still refers to the parameter, and later lines see the sorted array. The caller's array is unchanged. sorted()againstsort().sorted()returns a new sorted array, andsort()sorts in place, which needs avar.- Braces are required.
if i > 0 && nums[i] == nums[i - 1] { continue }fits on one line, but Swift never allows anifbody without braces. 0..<n - 2is a range up ton - 3. Forn = 2it is empty, but for fewer than two elements its end is below its start, which stops the program. The constraints promise at least 3 elements.- Two variables in one
var.var left = i + 1, right = n - 1declares both pointers on one line. - Nested array type.
[[Int]]()is an empty array whose elements are arrays ofInt.
Complexity
Time: O(n²). The sort costs O(n log n). The outer loop runs n - 2 times, and for each i the two pointers together move at most n steps, because every iteration of the inner loop moves at least one of them.
Space: O(1) extra, apart from the sorted copy and the returned triplets. The method keeps a few integers.
Edge cases and common mistakes
- No triplet.
[0, 1, 1]and[1, 2, 3]both return[]. - All zeros.
[0, 0, 0]and[0, 0, 0, 0]both return[[0, 0, 0]], once. - Repeated values.
[-2, 0, 1, 1, 2]returns[[-2, 0, 2], [-2, 1, 1]]. A triplet may use the same value twice when the array holds it twice. - Skipping duplicates of
ithe wrong way. Comparingnums[i]withnums[i + 1]would skip the first copy and lose triplets like[-1, -1, 2]. The check looks back atnums[i - 1], so the first copy of each value always gets its turn. - Forgetting to sort. Both the pointer moves and the duplicate skipping depend on the order.
- Forgetting to move the pointers after a match. The loop would find the same triplet forever.
- Using a set of triplets. It also removes duplicates, but it costs extra memory and the answer would need sorting afterwards.
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, 1, 1, 2]gives[[-2, 0, 2], [-2, 1, 1]].[-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]].
