Combine sorting and two pointers to find triples without duplicates.
Use it when you need three values with a total, closest to a total, or under a limit, and the order of the values does not matter. Signal words: three values, add up to, every distinct triple, closest to, how many triples.
Start sort a copy. For each first value at i, put left at i + 1 and right at the last index.
Step add the three values. Too small: move left. Too large: move right. Equal: record the triple, and move both pointers past equal values.
Stop when left meets right. Then move to the next first value, skipping a repeated one.
It does not need extra memory for the search. A hash set can also find triples, but it needs more memory and care with repeats.
Cost: n first values times at most n pointer moves: O(n^2) time, and O(n) for the sorted copy.
In this lesson you learn to find triples of values with a given total. You sort, fix one value, and let two pointers search for the other two.
A music streaming app builds mixes for its listeners. Each mix block must run for exactly 12 minutes, and it uses three different tracks. Your team lead asks for a tool that lists every possible block.
Your team lead says: Editors choose the tracks, so the tool must list every block that fills the 12 minutes exactly, with no repeats.
A block of the same three lengths counts once, and the editor waits for the answer on screen.
Here is a short test. A catalogue slice holds tracks of [3, 5, 4, 2, 6, 3, 7, 1] minutes. One block is 1 + 4 + 7 = 12. Another is 3 + 3 + 6 = 12, which uses the two different 3-minute tracks.
So the task is this: find every distinct triple of lengths that add up to 12, fast.
Picture a pantry shelf of tins, sorted by weight from light to heavy. You need three tins that weigh exactly 600 grams together.
You pick one tin and put it aside. Now you need two tins from the rest that make up the remainder. You put one hand on the lightest tin and one on the heaviest, and you check the pair.
If the pair is too light, you move the light hand to a heavier tin. If it is too heavy, you move the heavy hand to a lighter tin. You pick the next tin to put aside, and you do it again. The tin you set aside, and the two hands, are the three values of this lesson.
Set one item aside and the question shrinks to one you already know: find two that make what is left.
Before you write code, find the blocks for the test list by hand. It shows you where the work goes.
Solve it by hand: Track lengths by hand: three tracks for a 12-minute mix. The hand-solve sheet loads in your browser.
You work at the whiteboard. You write the lengths in order, and you list the groups of three one by one. You cross out each group whose total is not 12.
Input: [3, 5, 4, 2, 6, 3, 7, 1], target 12. Sorted, the lengths are [1, 2, 3, 3, 4, 5, 6, 7].
| First | Second | Third | Total | your note |
|---|---|---|---|---|
| 1 | 2 | 3 | 6 | too small |
| 1 | 2 | 3 | 6 | the other 3: the same lengths again |
| 1 | 2 | 4 | 7 | too small |
| 1 | 4 | 7 | 12 | a block: write it down |
| 1 | 5 | 6 | 12 | a block: write it down |
| 2 | 3 | 7 | 12 | a block: write it down |
| 2 | 3 | 7 | 12 | the other 3: write it once only |
| 3 | 3 | 6 | 12 | a block: write it down |
The table shows 8 of the 56 groups you checked. In the end, you have six distinct blocks: 1 + 4 + 7, 1 + 5 + 6, 2 + 3 + 7, 2 + 4 + 6, 3 + 3 + 6 and 3 + 4 + 5. You also checked every group twice, once for each 3-minute track.
Look at what costs you time. For every first track you check every second and third track, even when the total is far too small.
Remember this. You will use it soon.
You turn the hand method into code.
Start with a correct version. Use three loops, one per track, and check every total.
def triples_by_loops(values, target):
found = set()
n = len(values)
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if values[i] + values[j] + values[k] == target:
found.add(tuple(sorted((values[i], values[j], values[k]))))
return sorted(found)This is correct. The set removes repeats, and the sorted result is stable. It checks every group of three, so it makes n × (n − 1) × (n − 2) / 6 checks, and it is O(n^3). The team keeps it as the reference.
Now check real catalogues.
A mood catalogue has about 3,000 tracks, and the editor waits on screen. Two seconds is the limit.
Here is the count for one catalogue:
So the first attempt takes more than 20 times the budget. Doubling the catalogue would make it eight times slower. The team needs a method that does not look at every group of three.
Predict the cost
Q A catalogue holds 3,000 tracks, and the first attempt checks every group of three. About how long does it take at 10^8 operations a second?
Answer: C
The number of groups is 3,000 × 2,999 × 2,998 / 6, which is about 4.5 billion. At 10^8 checks a second that is about 45 seconds, far over the 2 second budget.
The first attempt is correct, but it grows with the cube of the catalogue. Now the team looks for the checks it can skip.
Look at the table of totals on the whiteboard.
Fix the first track. What is left is a pair that makes the rest, and you know that search. Can we do better?
You know this pair search from the opposite-ends lesson. In a sorted list, one pointer at each end finds two values with a given total in one pass. A total that is too small rules out the left value. A total that is too large rules out the right value.
For 3-sum, you do not need the three values at once. Pick the first value, and the other two must add up to the target minus the first. That is a pair search on the values after it. So the method is:
i. Run left from i + 1 and right from the last index.There are n choices for the first value, and each pair search takes at most n steps. So the total is about n × n steps, which is O(n^2).
| Step | i | left, right | Total | What happens |
|---|---|---|---|---|
| 1 | 0 | 1, 7 | 1 + 2 + 7 = 10 | too small: left moves to 2 |
| 2 | 0 | 2, 7 | 1 + 3 + 7 = 11 | too small: left moves to 3 |
| 3 | 0 | 3, 7 | 1 + 3 + 7 = 11 | too small: left moves to 4 |
| 4 | 0 | 4, 7 | 1 + 4 + 7 = 12 | match: record [1, 4, 7], left 5, right 6 |
| 5 | 0 | 5, 6 | 1 + 5 + 6 = 12 | match: record [1, 5, 6], pointers meet |
| 6 | 1 | 2, 7 | 2 + 3 + 7 = 12 | match: record [2, 3, 7], left 4 (past the other 3), right 6 |
| 7 | 1 | 4, 6 | 2 + 4 + 6 = 12 | match: record [2, 4, 6], pointers meet |
| 8 | 2 | 3, 7 | 3 + 3 + 7 = 13 | too large: right moves to 6 |
| 9 | 2 | 3, 6 | 3 + 3 + 6 = 12 | match: record [3, 3, 6], left 4, right 5 |
| 10 | 2 | 4, 5 | 3 + 4 + 5 = 12 | match: record [3, 4, 5], pointers meet |
After step 10, index 3 holds 3 again, so it is skipped. The first values 4 and 5 find nothing. The result is the six blocks, after 13 total checks instead of 56 group checks, and each block is recorded once.
Race: Every triple, against fix one and run two pointers. The operation counter loads in your browser.
The race counts how many totals each version checks on random track lengths. At 300 tracks, the loops check 4,455,100 groups. The pointer version checks 36,019 totals. The gap widens fast, because one grows with n^3 and the other with n^2.
3-sum: sort, fix the first value, then run opposite-end pointers on the rest, moving the one that fixes the total.
To record each block once, skip a repeated first value, and after a match move both pointers past equal values.
A second list of tracks, [2, 2, 2, 4, 6, 6, 8], also needs blocks of 12. The player stops at five steps and asks you to predict.
Dry run: Predict each step: a second list of tracks. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Step | i | left, right | Total | What happens |
|---|---|---|---|---|
| 1 | 0 | 1, 6 | 2 + 2 + 8 = 12 | match: record [2, 2, 8], left 3 (past the other 2), right 5 |
| 2 | 0 | 3, 5 | 2 + 4 + 6 = 12 | match: record [2, 4, 6], left 4, right 4 |
| 3 | 1 | first value 2 repeats: skip | ||
| 4 | 2 | first value 2 repeats: skip | ||
| 5 | 3 | 4, 6 | 4 + 6 + 8 = 18 | too large: right moves to 5 |
| 6 | 3 | 4, 5 | 4 + 6 + 6 = 16 | too large: right moves to 4, the pointers meet |
| 7 | 4 | 5, 6 | 6 + 6 + 8 = 20 | too large: right moves to 5, the pointers meet |
Look at steps 3 and 4. Three tracks of 2 minutes would give the same blocks three times. Skipping the repeated first values keeps each block once.
Exercise · Predict the output: Which triples are recorded?. The sorted track lengths are below, and the target is 0. The code prints each recorded triple, separated by spaces. What does it print?
values = [-1, -1, 0, 0, 1, 1, 2]
target = 0
n = len(values)
found = []
for i in range(n - 2):
if i > 0 and values[i] == values[i - 1]:
continue
left, right = i + 1, n - 1
while left < right:
total = values[i] + values[left] + values[right]
if total < target:
left += 1
elif total > target:
right -= 1
else:
found.append(f"{values[i]},{values[left]},{values[right]}")
left += 1
right -= 1
while left < right and values[left] == values[left - 1]:
left += 1
while left < right and values[right] == values[right + 1]:
right -= 1
print(" ".join(found))Here is the rule that keeps the search correct. Every line of the templates below exists to protect it.
For each first value, every pair that uses a value outside left..right has been recorded or ruled out, and no triple has been recorded twice.
At the start of a pair search, left is i + 1 and right is the last index, so every pair lies inside left..right. A total that is too small rules out left: every pair that uses this left and a smaller right is smaller still. A total that is too large rules out right in the same way.
After a match, the pair is recorded and both pointers move. Moving them past equal values stops the same triple from being found again. A repeated first value is skipped for the same reason.
Use it when you need three values with a total, closest to a total, or under a limit, and the order of the values does not matter. Signal words: three values, add up to, every distinct triple, closest to, how many triples.
Start: sort a copy. For each first value at i, put left at i + 1 and right at the last index.
Step: add the three values. Too small: move left. Too large: move right. Equal: record the triple, and move both pointers past equal values.
Stop: when left meets right. Then move to the next first value, skipping a repeated one.
It does not need extra memory for the search. A hash set can also find triples, but it needs more memory and care with repeats.
Cost: n first values times at most n pointer moves: O(n^2) time, and O(n) for the sorted copy.
def triples_to_target(values, target):
# [1] Sort a copy, so the pair search can move its pointers by size and equal values sit together.
ordered = sorted(values)
n = len(ordered)
found = []
for i in range(n - 2):
# [2] Skip a first value equal to the one before it: it would only repeat the same triples.
if i > 0 and ordered[i] == ordered[i - 1]:
continue
# [3] Search the values after i from both ends for the pair that completes the target.
left = i + 1
right = n - 1
while left < right:
total = ordered[i] + ordered[left] + ordered[right]
# [4] Too small: every pair with this left and a smaller right is smaller still, so rule out left.
if total < target:
left += 1
# [5] Too large: every pair with this right and a larger left is larger still, so rule out right.
elif total > target:
right -= 1
else:
# [6] Equal: record the triple, then step both pointers past their equal values so it is not recorded twice.
found.append([ordered[i], ordered[left], ordered[right]])
left += 1
right -= 1
while left < right and ordered[left] == ordered[left - 1]:
left += 1
while left < right and ordered[right] == ordered[right + 1]:
right -= 1
# [7] Report the triples, found in order.
return foundpublic int[][] triplesToTarget(int[] values, int target) {
// [1] Sort a copy, so the pair search can move its pointers by size and equal values sit together.
int[] ordered = values.clone();
java.util.Arrays.sort(ordered);
int n = ordered.length;
java.util.List<int[]> found = new java.util.ArrayList<>();
for (int i = 0; i < n - 2; i++) {
// [2] Skip a first value equal to the one before it: it would only repeat the same triples.
if (i > 0 && ordered[i] == ordered[i - 1]) {
continue;
}
// [3] Search the values after i from both ends for the pair that completes the target.
int left = i + 1;
int right = n - 1;
while (left < right) {
int total = ordered[i] + ordered[left] + ordered[right];
// [4] Too small: every pair with this left and a smaller right is smaller still, so rule out left.
if (total < target) {
left++;
}
// [5] Too large: every pair with this right and a larger left is larger still, so rule out right.
else if (total > target) {
right--;
} else {
// [6] Equal: record the triple, then step both pointers past their equal values so it is not recorded twice.
found.add(new int[] {ordered[i], ordered[left], ordered[right]});
left++;
right--;
while (left < right && ordered[left] == ordered[left - 1]) {
left++;
}
while (left < right && ordered[right] == ordered[right + 1]) {
right--;
}
}
}
}
// [7] Report the triples, found in order.
return found.toArray(new int[0][]);
}vector<vector<int>> triplesToTarget(vector<int>& values, int target) {
// [1] Sort a copy, so the pair search can move its pointers by size and equal values sit together.
vector<int> ordered(values);
sort(ordered.begin(), ordered.end());
int n = (int) ordered.size();
vector<vector<int>> found;
for (int i = 0; i < n - 2; i++) {
// [2] Skip a first value equal to the one before it: it would only repeat the same triples.
if (i > 0 && ordered[i] == ordered[i - 1]) {
continue;
}
// [3] Search the values after i from both ends for the pair that completes the target.
int left = i + 1;
int right = n - 1;
while (left < right) {
int total = ordered[i] + ordered[left] + ordered[right];
// [4] Too small: every pair with this left and a smaller right is smaller still, so rule out left.
if (total < target) {
left++;
}
// [5] Too large: every pair with this right and a larger left is larger still, so rule out right.
else if (total > target) {
right--;
} else {
// [6] Equal: record the triple, then step both pointers past their equal values so it is not recorded twice.
found.push_back({ordered[i], ordered[left], ordered[right]});
left++;
right--;
while (left < right && ordered[left] == ordered[left - 1]) {
left++;
}
while (left < right && ordered[right] == ordered[right + 1]) {
right--;
}
}
}
}
// [7] Report the triples, found in order.
return found;
}function triplesToTarget(values, target) {
// [1] Sort a copy, so the pair search can move its pointers by size and equal values sit together.
const ordered = [...values].sort((a, b) => a - b);
const n = ordered.length;
const found = [];
for (let i = 0; i < n - 2; i++) {
// [2] Skip a first value equal to the one before it: it would only repeat the same triples.
if (i > 0 && ordered[i] === ordered[i - 1]) {
continue;
}
// [3] Search the values after i from both ends for the pair that completes the target.
let left = i + 1;
let right = n - 1;
while (left < right) {
const total = ordered[i] + ordered[left] + ordered[right];
// [4] Too small: every pair with this left and a smaller right is smaller still, so rule out left.
if (total < target) {
left++;
}
// [5] Too large: every pair with this right and a larger left is larger still, so rule out right.
else if (total > target) {
right--;
} else {
// [6] Equal: record the triple, then step both pointers past their equal values so it is not recorded twice.
found.push([ordered[i], ordered[left], ordered[right]]);
left++;
right--;
while (left < right && ordered[left] === ordered[left - 1]) {
left++;
}
while (left < right && ordered[right] === ordered[right + 1]) {
right--;
}
}
}
}
// [7] Report the triples, found in order.
return found;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The first value that never runs. This function counts the distinct triples of values with a given total. It misses a triple on some inputs. Which line is wrong?
def count_triples(values, target):
ordered = sorted(values)
n = len(ordered)
count = 0
for i in range(n - 3):
if i > 0 and ordered[i] == ordered[i - 1]:
continue
left, right = i + 1, n - 1
while left < right:
total = ordered[i] + ordered[left] + ordered[right]
if total < target:
left += 1
elif total > target:
right -= 1
else:
count += 1
left += 1
right -= 1
while left < right and ordered[left] == ordered[left - 1]:
left += 1
while left < right and ordered[right] == ordered[right + 1]:
right -= 1
return countSome questions ask how many triples fit, not which ones. Then the pointers can count whole groups at once.
Suppose the total at left and right is under the limit. Then every right from left + 1 up to the current right is also under the limit, because those values are no larger. Add right - left triples, and move left on.
Here triples are counted by position, so equal values at different positions count separately, and no repeat skipping is needed.
def count_under(values, limit):
# [1] Sort a copy: reordering the values does not change how many triples fit.
ordered = sorted(values)
n = len(ordered)
count = 0
for i in range(n - 2):
# [2] Fix the first value at i and search the values after it from both ends.
left = i + 1
right = n - 1
while left < right:
# [3] Under the limit: left fits with every value from left + 1 to right, so count them all and rule out left.
if ordered[i] + ordered[left] + ordered[right] < limit:
count += right - left
left += 1
# [4] Not under the limit: this right is too large for every left, so rule out right.
else:
right -= 1
# [5] Report the count.
return countpublic long countUnder(int[] values, long limit) {
// [1] Sort a copy: reordering the values does not change how many triples fit.
int[] ordered = values.clone();
java.util.Arrays.sort(ordered);
int n = ordered.length;
long count = 0; // up to about n^3 / 6 triples, beyond a 32-bit int
for (int i = 0; i < n - 2; i++) {
// [2] Fix the first value at i and search the values after it from both ends.
int left = i + 1;
int right = n - 1;
while (left < right) {
// [3] Under the limit: left fits with every value from left + 1 to right, so count them all and rule out left.
if ((long) ordered[i] + ordered[left] + ordered[right] < limit) {
count += right - left;
left++;
}
// [4] Not under the limit: this right is too large for every left, so rule out right.
else {
right--;
}
}
}
// [5] Report the count.
return count;
}long long countUnder(vector<int>& values, long long limit) {
// [1] Sort a copy: reordering the values does not change how many triples fit.
vector<int> ordered(values);
sort(ordered.begin(), ordered.end());
int n = (int) ordered.size();
long long count = 0; // up to about n^3 / 6 triples, beyond a 32-bit int
for (int i = 0; i < n - 2; i++) {
// [2] Fix the first value at i and search the values after it from both ends.
int left = i + 1;
int right = n - 1;
while (left < right) {
// [3] Under the limit: left fits with every value from left + 1 to right, so count them all and rule out left.
if ((long long) ordered[i] + ordered[left] + ordered[right] < limit) {
count += right - left;
left++;
}
// [4] Not under the limit: this right is too large for every left, so rule out right.
else {
right--;
}
}
}
// [5] Report the count.
return count;
}function countUnder(values, limit) {
// [1] Sort a copy: reordering the values does not change how many triples fit.
const ordered = [...values].sort((a, b) => a - b);
const n = ordered.length;
let count = 0; // up to about n^3 / 6 triples, exact in a JavaScript number
for (let i = 0; i < n - 2; i++) {
// [2] Fix the first value at i and search the values after it from both ends.
let left = i + 1;
let right = n - 1;
while (left < right) {
// [3] Under the limit: left fits with every value from left + 1 to right, so count them all and rule out left.
if (ordered[i] + ordered[left] + ordered[right] < limit) {
count += right - left;
left++;
}
// [4] Not under the limit: this right is too large for every left, so rule out right.
else {
right--;
}
}
}
// [5] Report the count.
return count;
}The 3-sum template, line by line: sort, fix a first value, move left and right, and skip equal values.
Exercise · Put it in order: Count the pairs for one first value. The values are sorted. Arrange the lines into a search that counts the pairs after index i whose total with values[i] is under the limit.
def count_pairs_after(ordered, i, limit):
count = 0
left, right = i + 1, len(ordered) - 1
while left < right:
if ordered[i] + ordered[left] + ordered[right] < limit:
count += right - left
left += 1
else:
right -= 1
return count
count += right - left + 1A ride-hailing app batches three trips for one driver, and a batch must take less than 100 minutes in all. The queue holds trips of [20, 60, 30, 50, 40, 10] minutes. How many batches fit?
This is Template 2 with limit = 100. Sorted, the trips are [10, 20, 30, 40, 50, 60].
| i | left | right | Total | What happens | count after |
|---|---|---|---|---|---|
| 0 | 1 | 5 | 10 + 20 + 60 = 90 | under: add 5 − 1 = 4, left moves | 4 |
| 0 | 2 | 5 | 10 + 30 + 60 = 100 | not under 100: right moves | 4 |
| 0 | 2 | 4 | 10 + 30 + 50 = 90 | under: add 4 − 2 = 2, left moves | 6 |
| 0 | 3 | 4 | 10 + 40 + 50 = 100 | not under 100: right moves, pointers meet | 6 |
| 1 | 2 | 5 | 20 + 30 + 60 = 110 | not under: right moves | 6 |
| 1 | 2 | 4 | 20 + 30 + 50 = 100 | not under: right moves | 6 |
| 1 | 2 | 3 | 20 + 30 + 40 = 90 | under: add 3 − 2 = 1, left moves | 7 |
| 2 | 3 | 5 | 30 + 40 + 60 = 130 | not under: right moves | 7 |
| 2 | 3 | 4 | 30 + 40 + 50 = 120 | not under: right moves, pointers meet | 7 |
| 3 | 4 | 5 | 40 + 50 + 60 = 150 | not under: right moves, pointers meet | 7 |
Seven batches fit. The first row shows the saving. One check at 10 + 20 + 60 counts four batches at once, because 10 + 20 + 30, 10 + 20 + 40 and 10 + 20 + 50 are all smaller.
Real production data brings edge cases.
A tiny catalogue holds [1, 2], and the target is 3. The loop for i in range(n - 2) has no iterations when n is 2, so the answer is an empty list.
An empty catalogue works the same way. A negative range count would be a bug in some languages, so test it.
For [3, 3, 3, 3] and a target of 9, the answer is one triple: [[3, 3, 3]]. The first value at index 0 finds it. The skips make indexes 1 and 2 repeat the same first value, so they add nothing.
Without the skips, the same triple would be recorded several times.
Values may be negative or zero, such as temperature changes. For [-1, 0, 1, 2, -1, -4] and a target of 0, the answer is [[-1, -1, 2], [-1, 0, 1]]. The pointers work the same way.
For [0, 0, 0] and a target of 0, the answer is [[0, 0, 0]]. One triple uses three equal values.
Two tracks of 3 minutes are different tracks. In [2, 3, 3, 6] with a target of 12, the answer is [[3, 3, 6]], and 2 + 3 + 6 is not 12.
A value may appear twice in a triple only if it appears twice in the list. The pointers use different indexes, so this is true without extra code.
Exercise · Break it: Find the input that counts a triple twice. This function counts the distinct triples with a given total. It skips equal values after a match, but it has no check for a repeated first value. Find an input where it counts a triple more than once.
def count_triples(values, target):
ordered = sorted(values)
n = len(ordered)
count = 0
for i in range(n - 2):
left, right = i + 1, n - 1
while left < right:
total = ordered[i] + ordered[left] + ordered[right]
if total < target:
left += 1
elif total > target:
right -= 1
else:
count += 1
left += 1
right -= 1
while left < right and ordered[left] == ordered[left - 1]:
left += 1
while left < right and ordered[right] == ordered[right + 1]:
right -= 1
return countThis version skips a first value when it equals the next one, not the one before:
if ordered[i] == ordered[i + 1]: # bug: looks forward
continueCounterexample: values = [1, 1, 2], target 4. The bug returns []. The correct answer is [[1, 1, 2]].
At index 0 the first 1 equals the next value, so it is skipped. Then index 1 has no pair left. Looking back, at ordered[i - 1], skips only a first value whose triples were already found.
Skip a repeated first value by comparing with the one before it, not the next one, or you miss a block.
This version moves both pointers by one after a match, and does not skip equal values:
found.append([ordered[i], ordered[left], ordered[right]])
left += 1
right -= 1 # bug: an equal value may match againCounterexample: values = [2, 2, 2, 2, 2], target 6. The bug returns [[2, 2, 2], [2, 2, 2]]. The correct answer is [[2, 2, 2]].
After the first match, left and right land on more 2s, and they match again. Skipping equal values after a match stops the repeat.
After a match, move both pointers past equal values, or the same triple is recorded again and again.
A tempting shortcut is to run the pointers on the raw list, because it saves the sort.
Counterexample: values = [1, 8, 7, 3, 2], target 12. The bug returns [[7, 3, 2]]. The correct answer has two triples: [[1, 3, 8], [2, 3, 7]].
The pointer rule says that a total too small rules out the left value, because the values after it are larger. That is only true when the list is sorted. Sort a copy first.
Your team lead asks for blocks of any size: choose as many tracks as you like, with a total of exactly 12 minutes. For [3, 5, 4, 2, 6, 3, 7, 1], that includes 5 + 7 and 1 + 2 + 3 + 6.
Two pointers handle a fixed number of values: a fixed number of loops, and a pair at the end. With any number of values, there is no fixed first choice. Subset sums are solved with dynamic programming, a later module.
Your team lead brings four product changes. Each one keeps the idea of fixing a value and searching the rest with two pointers.
A parcel-delivery app loads three parcels on a pallet, and the total should be as close as possible to the pallet's rated load. For the weights [42000, 15000, 31000, 26000, 58000, 9000] and a limit of 105000, the closest total is 104000.
Keep the closest total so far as the pointers move. An exact match ends the search. It is the second practice problem (LeetCode 16: 3Sum Closest).
An ad platform counts the triples of bids under a page budget. When the total at left and right fits, every right between them fits too, so the count grows by right - left. It is the third practice problem (LeetCode 259: 3Sum Smaller).
A payments app looks for four adjustments that net to zero. Fix two values with two loops and run the pair search inside: O(n^3). When the values come in four lists, add the pairs of two lists and match them against the pairs of the other two (LeetCode 18: 4Sum).
A parcel-delivery app asks how many triples of crate edges can form a triangle. Three lengths form a triangle when the two shorter ones add up to more than the longest. For the edges [2, 3, 4, 5], there are 3 triangles.
Sort, fix the longest edge, and count the pairs of shorter edges whose total is above it. It is the same count-by-range trick as Template 2 (LeetCode 611: Valid Triangle Number).
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate why 3-sum takes O(n^2) time and not O(n^3). Then explain how the search avoids recording the same triple twice. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have built it.
I sort a copy, fix the first value, and search the rest with a left and a right pointer.
Too small moves left, too large moves right. A match is recorded, and both pointers skip equal values.
That is n first values times at most n moves each: O(n squared). A repeated first value is skipped.
Three values with a given total, with no repeated triples, is a 3-sum. Checking every triple is O(n^3), which is too slow at a few thousand values.
I sort a copy. Then for each first value, I run the opposite-ends pair search on the values after it, with left after the first value and right at the end.
If the total is too small, I move left, because every pair with a smaller right is smaller still. If it is too large, I move right.
When the total matches, I record the triple and move both pointers past equal values. I also skip a first value that equals the one before it, so no triple repeats.
Each first value costs at most n moves, so it is O(n squared) time and O(n) space for the sorted copy. I would test fewer than three values, all values equal, and negative values.
Checkpoint · Merging
Q1/3 Two sorted lists have fronts 9 and 6. A merge has taken 4 so far. What does it take next?
Answer: B
Each list is sorted, so the smallest value left is one of the two fronts. Take the smaller and move only its pointer.
Q2/3 A merge loop ends because the first list ran out. The second list still holds values. What must the code do?
Answer: C
Everything left is larger than all values taken, and it is already in order. Forgetting this tail is Exhibit 1 in the mistake museum.
Q3/3 Two sorted lists of n and m values are merged. How many steps does the merge make at most?
Answer: C
Every step takes one value and no pointer goes back, so there are at most n + m steps.
Checkpoint · 3-sum
Q1/6 Which request is a job for 3-sum?
Answer: C
Three values with a total, with no repeated groups, are the signals. The sorted logs are a merge, the pair is opposite ends, and the run is a sliding window.
Q2/6 What is the first step of the 3-sum method?
Answer: C
Sorting lets the pointers move by size. Fixing the first value turns the rest into the pair search from the opposite-ends lesson.
Q3/6 In the pair search for a fixed first value, the total is below the target. What do you do?
Answer: B
A total that is too small cannot be fixed by a smaller right value. So left cannot take part in any pair that is still unchecked.
Q4/6 The sorted list is [1, 1, 2] and the target is 4. A version skips the first value when ordered[i] == ordered[i + 1]. What does it return?
Answer: B
It skips index 0 because the next value is equal, and index 1 has no pair left. Skipping when the value equals the one before it, ordered[i - 1], is correct.
Q5/6 After a match, the code only does left += 1 and right -= 1. On [2, 2, 2, 2, 2] with target 6, what goes wrong?
Answer: C
After the first match, left and right land on more 2s and match again. Moving past equal values after a match stops the repeat.
Q6/6 Three loops over 3,000 values make about 4.5 billion checks. About how many steps does fix-one-and-two-pointers make at most?
Answer: C
There are n choices for the first value, and each pair search makes at most n moves, so the search is O(n squared): at most 4.5 million steps at n = 3,000.
Checkpoint · Counting
Q In Template 2, the total at left and right is under the limit. How many triples does it count, and why?
Answer: B
Values to the left of right are no larger, so every one of them also makes a total under the limit with this first value and left. Count them all, then move left.
Ten questions on this lesson and the last one. Pass with 80% or more, and solve the checkpoint's two mixed problems, to open the gate to the next part of the Academy map. The two problems are "Closest balance snapshots of two accounts" and "Four batches that net to zero".
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Three products for a gift card | Shop | Medium | Template 1: every distinct triple, with no repeats |
| 2 | Three parcels closest to the pallet limit | Freight | Medium | The pair search, keeping the closest total |
| 3 | Ad slot triples under the page budget | Ads | Medium | Template 2: count whole groups at once |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.