Problem overview
The function three_sum receives a vector of integers, nums, and returns every triplet of values that adds up to 0, taken from three different positions. The answer must not repeat a triplet: three values count once however many index combinations produce them. Each triplet is written in ascending order, and the triplets are returned in ascending order too, comparing first values, then second values, then third values.
For [-1, 0, 1, 2, -1, -4] the answer is [[-1, -1, 2], [-1, 0, 1]]. For [0, 0, 0, 0] it is [[0, 0, 0]]: many index choices give 0 + 0 + 0, but they form one triplet. For [0, 1, 1] it is an empty vector. The limit is O(n²) time, ignoring the sort and the output.
Approach: fix one number, then run two pointers
Trying every triple of indices takes O(n³) time, and removing duplicates afterwards needs extra bookkeeping. Sorting first changes the problem in two ways.
- Equal values sit side by side, so duplicates can be skipped by comparing a value with its neighbour.
- A sorted vector tells the pointers which way to move. Fix the first number at
i. Putleftjust after it andrightat the end. If the sum is too small, only a bigger value atleftcan raise it, soleftmoves right. If the sum is too large,rightmoves left. If it is 0, record the triplet and move both inward.
Each value of i costs one pass of the two pointers, O(n), so the whole scan is O(n²). Because the vector is sorted and i < left < right, each triplet is already in ascending order, and scanning left to right produces the triplets in ascending order as well, so no final sort is needed.
Here is the scan on [-1, 0, 1, 2, -1, -4]. The sorted vector is [-4, -1, -1, 0, 1, 2], and the steps are:
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
With i = 0 (value -4) the sums are always too small, so left moves until the pointers meet. With i = 1 (value -1) the first sum is -1 + -1 + 2 = 0, which gives [-1, -1, 2], and then -1 + 0 + 1 = 0 gives [-1, 0, 1]. At i = 2 the value -1 repeats the previous one, so it is skipped.
Step by step
- Sort
nums. The parameter is immutable, so bind it again withlet mut nums = nums;and callsort(), which sorts in place. - Store the length in
n, used for the loop bounds. - Create
resultas an emptyVec<Vec<i32>>. Each element will be one triplet. - Loop over the first number with
igoing over0..n - 2, because two more values must follow it. - Skip a repeated first number: if
i > 0andnums[i]equalsnums[i - 1],continue. The same first value would find the same triplets again. - Set the pointers:
leftati + 1andrightatn - 1, both mutable. - Loop while
left < right. When they meet, every pair for thisihas been tried. - Compute
totalasnums[i] + nums[left] + nums[right]. - Total below 0: add 1 to
left. - Total above 0: subtract 1 from
right. - Otherwise the total is 0: push
vec![nums[i], nums[left], nums[right]]ontoresult. - Move both pointers inward. Keeping one in place would need the other one's old value again, and that repeats the triplet.
- Skip repeats of the second number: while
left < rightandnums[left]equalsnums[left - 1], ... - ...add 1 to
left. - Return
resultas the last expression.
The solution in Rust
impl Solution {
fn three_sum(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut nums = nums;
nums.sort();
let n = nums.len();
let mut result: Vec<Vec<i32>> = Vec::new();
for i in 0..n - 2 {
if i > 0 && nums[i] == nums[i - 1] {
continue;
}
let mut left = i + 1;
let mut 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.push(vec![nums[i], nums[left], nums[right]]);
left += 1;
right -= 1;
while left < right && nums[left] == nums[left - 1] {
left += 1;
}
}
}
}
result
}
}
The Rust details worth a closer look:
- Shadowing to get mutability.
let mut nums = nums;moves the vector into a new mutable binding with the same name. The alternative is to declare the parameter asmut numsin the signature, but the lesson keeps the signature as given. usizearithmetic.n - 2would underflow for fewer than two elements, andright -= 1would underflow ifrightwere 0. The first can't happen because the constraints guarantee at least 3 numbers. The second can't happen because the loop only runs whileleft < right, sorightis at least 1.- The range
0..n - 2excludes its end, soistops atn - 3, the last index that still has two values after it. vec![a, b, c]builds a vector from its elements, andpushmoves it intoresult.- Sum overflow. The values are at most 100,000 in absolute value, so a sum of three is far below the
i32limit. - Why only
leftskips duplicates. After a match, a repeated value atleftwould pair with the samerightand rebuild the same triplet, so the loop steps past it. A repeated value atrightneeds no loop: next to the biggerleft, it makes the total positive, and the positive-total branch movesrightby itself.
Complexity
Time: O(n²). Sorting costs O(n log n). For each i, left only moves right and right only moves left, so the pointer loop makes at most n steps. With up to n values of i, that is O(n²), which dominates the sort.
Space: O(1) beyond the sort and the output. The code uses a few integers, and the triplets it returns are the answer itself. The sort is done in place on the vector the function owns.
Edge cases and common mistakes
- All zeros.
[0, 0, 0, 0]gives[[0, 0, 0]], one triplet, although four positions can be chosen three at a time in several ways. The skip of a repeatediis what keeps the later zeros from adding the triplet again. - Repeated values that still form one triplet.
[-2, 0, 0, 2, 2]gives[[-2, 0, 2]], even though the 0s and 2s can be chosen in several ways. After the first match, the skip of the repeated 0 atleftstops the second 0 and 2 from recording it again. - No answer.
[0, 1, 1]gives[]. - Three values only.
[3, -1, -2]gives[[-2, -1, 3]]: the triplet is written in ascending order, not in the input order. - Using the same position twice. The pointers satisfy
i < left < right, so a position is never used twice, while two equal values at different positions are fine, as in[-1, -1, 2]. - Forgetting the skip of a repeated
i. The two-1values in the first example would each start a scan and the triplet[-1, 0, 1]would appear twice.
Testing
nums = [-1, 0, 1, 2, -1, -4]gives[[-1, -1, 2], [-1, 0, 1]].nums = [0, 1, 1]gives[].nums = [0, 0, 0, 0]gives[[0, 0, 0]].nums = [-2, 0, 0, 2, 2]gives[[-2, 0, 2]].nums = [-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]].
