Move pointers inward from both ends of a sorted sequence.
Use it when the values are sorted, or can be sorted, and the question is about a pair. Signal words: sorted, two values, add up to, closest to, within a budget, from both ends, palindrome, reverse.
Start left on the first index, right on the last.
Step compare the two values with the target. Too small, move left in. Too large, move right in. Each move rules out one value for good.
Stop when left meets right. Use left < right, so a value is never paired with itself.
Counting when a total fits within a limit, the value at left fits with every value from left + 1 to right. Add right − left in one step.
It needs sorted values. On unsorted values, sort them first, or use a hash map when you must keep the original positions.
Cost: at most n − 1 steps, so O(n) time and O(1) extra space.
In this lesson you learn to find a pair of values in a sorted list in one pass. You put one pointer at each end and move them inward, and every step rules out one value for good.
A delivery truck is about to leave a hub, and it still has some room. Your team lead sets the requirement for the dispatch screen.
Your team lead says: When a truck has spare capacity, dispatch wants two waiting parcels that fill it exactly, so the truck leaves full.
The screen must suggest the pair within one second. If no pair fits, it should say so.
The hub keeps its waiting parcels in a list sorted by weight, from the lightest to the heaviest. Here is one short test list, in kilograms: [4, 7, 11, 15, 20, 26, 31]. The truck has 37 kg of room.
So the task is this: find two different parcels whose weights add up to exactly 37.
Picture a shelf of books sorted by thickness, from the thinnest on the left to the thickest on the right. You need two books that together fill a gap of exactly 9 cm on another shelf. Put your left hand on the thinnest book and your right hand on the thickest.
If the two books together are too thick, the thickest book is too thick even with the thinnest one. It can never fit, so you put it aside and your right hand moves one book in. If they are too thin, the thinnest book is too thin even with the thickest, so it goes aside and your left hand moves in.
Your two hands are the two pointers: left and right. Putting a book aside is ruling it out. You never pick it up again, so each book costs you at most one look.
A shelf of books sorted by thickness: one hand on the thinnest, one on the thickest, and each check sets one book aside.
Before you write code, solve the test list by hand. It takes two minutes, and it shows you where the work goes.
Solve it by hand: The loading list by hand: two parcels that fill 37 kg. The hand-solve sheet loads in your browser.
You work through it on the whiteboard. You take each parcel in turn as the first parcel. Then you add it to every heavier parcel and looks for 37.
Input: [4, 7, 11, 15, 20, 26, 31], spare capacity 37 kg.
| First parcel | Partners tried | Totals | Fills 37? |
|---|---|---|---|
| 4 | 7, 11, 15, 20, 26, 31 | 11, 15, 19, 24, 30, 35 | no |
| 7 | 11, 15, 20, 26, 31 | 18, 22, 27, 33, 38 | no |
| 11 | 15, 20, 26 | 26, 31, 37 | yes: 11 + 26 |
The pair is the 11 kg and the 26 kg parcel, at indexes 2 and 5. You made 14 checks to find it.
Look at the last total in the first row. 4 + 31 = 35 is the largest total the 4 kg parcel can make, and it is still too light. The other five checks in that row could never have worked.
Remember this. You will use it soon.
You turn the hand method into code.
Start with a correct version. Try every pair, and return the first one that fills the truck.
def fill_pair(weights, spare):
for i in range(len(weights)):
for j in range(i + 1, len(weights)): # every heavier partner of parcel i
if weights[i] + weights[j] == spare:
return [i, j]
return [-1, -1]This is correct. For the test list it makes 14 checks, which takes no time at all. The team keeps it as the reference: every faster version must give the same answers.
How much work is it in general? With n parcels there are n × (n − 1) ÷ 2 pairs. When no pair fits, the first attempt checks every one of them.
Now check the real hubs.
At the evening peak, the central hubs hold up to 50,000 waiting parcels, and a truck leaves every few minutes.
Here is the count for one truck at such a hub:
Predict the cost
Q A computer does about 10^8 simple operations a second. About how long does the first attempt take for one truck?
Answer: C
1.25 × 10^9 ÷ 10^8 = 12.5 seconds. The screen must answer within 1 second, so the first attempt is more than 12 times too slow.
The first attempt is correct, but at this size it cannot keep up. Now the team looks for the work it repeats.
Look at the word "sorted" on the screen.
The list is sorted, and the first attempt never uses that. Can we do better?
Compare the lightest and the heaviest parcel first. On the test list, that is 4 + 31 = 35. It is too light.
Now think about the 4 kg parcel. Its heaviest possible partner is 31, and even that total is too light. Every other partner is lighter, so every other total is lighter still.
So the 4 kg parcel can never be part of the answer. You rule it out for good and move the left pointer one step in.
The next total is 7 + 31 = 38. It is too heavy. The 31 kg parcel overfills the truck even with 7, the lightest parcel still in play.
So the 31 kg parcel can never be part of the answer either. You rule it out and move the right pointer one step in.
That is the whole idea:
Two indexes that move through a list like this are called two pointers. Here they start at the two ends and move toward each other, so they are opposite-ends pointers. Sliding windows, in Module 5, are two pointers that move in the same direction.
| Left | Right | Weights | Total | Compared with 37 | Ruled out |
|---|---|---|---|---|---|
| 0 | 6 | 4 + 31 | 35 | too light | the 4 kg parcel |
| 1 | 6 | 7 + 31 | 38 | too heavy | the 31 kg parcel |
| 1 | 5 | 7 + 26 | 33 | too light | the 7 kg parcel |
| 2 | 5 | 11 + 26 | 37 | exact | none: return [2, 5] |
The pointers find the same pair as the hand method, with 4 checks instead of 14. Each check rules out one parcel, and a parcel that is ruled out never comes back. A list of n parcels can lose at most n − 1 of them before the pointers meet. So the pass makes at most n − 1 checks.
Race: First attempt against two pointers from opposite ends. The operation counter loads in your browser.
The race counts the pair checks of both versions when no pair fits. At 10,000 parcels, the first attempt makes 49,995,000 checks. The two pointers make 9,999. At 50,000 parcels, the pointers need at most 49,999 checks instead of about 1.25 × 10^9.
A second truck has 43 kg of room. Its hub's list is [8, 11, 13, 17, 22, 26, 31, 43]. The player stops at five steps and asks you to predict.
Dry run: Predict each move: two parcels that fill 43 kg. The step-by-step player loads in your browser.
Reading without the player? Cover the last two columns and predict them row by row.
| Left | Right | Weights | Total | Compared with 43 | Move |
|---|---|---|---|---|---|
| 0 | 7 | 8 + 43 | 51 | too heavy | right moves to 6 |
| 0 | 6 | 8 + 31 | 39 | too light | left moves to 1 |
| 1 | 6 | 11 + 31 | 42 | too light | left moves to 2 |
| 2 | 6 | 13 + 31 | 44 | too heavy | right moves to 5 |
| 2 | 5 | 13 + 26 | 39 | too light | left moves to 3 |
| 3 | 5 | 17 + 26 | 43 | exact | return [3, 5] |
Look at the fourth row. The total 44 is only 1 kg over, but close is not enough. The 31 kg parcel overfills even with 13, so it goes. The answer is the 17 kg and the 26 kg parcel.
Exercise · Predict the output: Where do the pointers stop?. A truck has 41 kg of room. The parcel weights are sorted. Where are left and right when the loop ends?
values = [2, 9, 14, 20, 27, 33]
target = 41
left, right = 0, len(values) - 1
while left < right:
total = values[left] + values[right]
if total == target:
break
if total < target:
left += 1
else:
right -= 1
print(left, right)Opposite ends: compare the total, then rule out one value for good. Too light moves left in, too heavy moves right in.
In Module 3 you met another way to find a pair: the seen set and the complement. You walk the list once. For each weight, you check whether spare − weight is already in a set, and then you add the weight.
That is also O(n) time, and it works on lists in any order. But the set can grow to hold every weight, so it needs O(n) extra memory. When the list is already sorted, two pointers find the pair with two indexes and one total: O(1) extra memory.
Here is the rule that keeps the pass correct. Every line of the templates below exists to protect it.
Every pair that uses a value outside left..right has already been ruled out, so if an answer exists, it lies inside left..right.
At the start, left..right is the whole list, so the rule holds.
Now say the total is too small. The value at left is too small even with the largest value inside left..right. Every value after right is already ruled out. So the value at left has no partner anywhere, and moving left keeps the rule true.
A total that is too large rules out the value at right in the same way. When the pointers meet, left..right holds one value, and one value cannot make a pair. So the answer is "no pair".
The rule also tells you which pair you get when there are several. A value is passed over only when it has no partner at all. So the first exact match has the smallest left index of any answer.
Use it when the values are sorted, or can be sorted, and the question is about a pair. Signal words: sorted, two values, add up to, closest to, within a budget, from both ends, palindrome, reverse.
Start: left on the first index, right on the last.
Step: compare the two values with the target. Too small, move left in. Too large, move right in. Each move rules out one value for good.
Stop: when left meets right. Use left < right, so a value is never paired with itself.
Counting: when a total fits within a limit, the value at left fits with every value from left + 1 to right. Add right − left in one step.
It needs sorted values. On unsorted values, sort them first, or use a hash map when you must keep the original positions.
Cost: at most n − 1 steps, so O(n) time and O(1) extra space.
def pair_with_sum(values, target):
# [1] Start with one pointer at each end.
left = 0
right = len(values) - 1
# [2] While two different values remain, compare their total with the target.
while left < right:
total = values[left] + values[right]
# [3] An exact match: return the two indexes.
if total == target:
return [left, right]
# [4] Too small: even the largest value still in play cannot lift values[left] to the target, so rule it out.
if total < target:
left += 1
# [5] Too large: even the smallest value still in play is too much for values[right], so rule it out.
else:
right -= 1
# [6] The pointers met: no pair adds up to the target.
return [-1, -1]public int[] pairWithSum(int[] values, long target) {
// [1] Start with one pointer at each end.
int left = 0;
int right = values.length - 1;
// [2] While two different values remain, compare their total with the target.
while (left < right) {
long total = (long) values[left] + values[right]; // 64-bit, so two large values cannot overflow
// [3] An exact match: return the two indexes.
if (total == target) {
return new int[] {left, right};
}
// [4] Too small: even the largest value still in play cannot lift values[left] to the target, so rule it out.
if (total < target) {
left++;
}
// [5] Too large: even the smallest value still in play is too much for values[right], so rule it out.
else {
right--;
}
}
// [6] The pointers met: no pair adds up to the target.
return new int[] {-1, -1};
}vector<int> pairWithSum(const vector<int>& values, long long target) {
// [1] Start with one pointer at each end.
int left = 0;
int right = (int) values.size() - 1;
// [2] While two different values remain, compare their total with the target.
while (left < right) {
long long total = (long long) values[left] + values[right]; // 64-bit, so two large values cannot overflow
// [3] An exact match: return the two indexes.
if (total == target) {
return {left, right};
}
// [4] Too small: even the largest value still in play cannot lift values[left] to the target, so rule it out.
if (total < target) {
left++;
}
// [5] Too large: even the smallest value still in play is too much for values[right], so rule it out.
else {
right--;
}
}
// [6] The pointers met: no pair adds up to the target.
return {-1, -1};
}function pairWithSum(values, target) {
// [1] Start with one pointer at each end.
let left = 0;
let right = values.length - 1;
// [2] While two different values remain, compare their total with the target.
while (left < right) {
const total = values[left] + values[right];
// [3] An exact match: return the two indexes.
if (total === target) {
return [left, right];
}
// [4] Too small: even the largest value still in play cannot lift values[left] to the target, so rule it out.
if (total < target) {
left++;
}
// [5] Too large: even the smallest value still in play is too much for values[right], so rule it out.
else {
right--;
}
}
// [6] The pointers met: no pair adds up to the target.
return [-1, -1];
}Rebuild the template: put its lines back in order. Loads in your browser.
The pair template line by line: pointers at both ends, compare the total, and move exactly one pointer in.
Exercise · Put it in order: The opposite-ends pair search. Arrange the lines into a search that returns the indexes of two parcels that add up to the target, or [-1, -1] when no pair does.
def pair_with_sum(values, target):
left = 0
right = len(values) - 1
while left < right:
total = values[left] + values[right]
if total == target:
return [left, right]
if total < target:
left += 1
else:
right -= 1
return [-1, -1]
while left <= right:Some questions ask how many pairs fit, not which pair. Say the total of the values at left and right is within the limit. Every value from left + 1 to right is no larger than the value at right, so each of them also fits with the value at left. That is right − left pairs, counted in one step.
Then the value at left has no uncounted partner, so left moves in.
def count_pairs_within(values, limit):
# [1] Start with one pointer at each end.
left = 0
right = len(values) - 1
count = 0
# [2] While two different values remain, compare their total with the limit.
while left < right:
# [3] It fits: values[left] fits with every value from left + 1 to right, so count them all.
if values[left] + values[right] <= limit:
count += right - left
left += 1
# [4] Too large: values[right] fits with no value still in play, so rule it out.
else:
right -= 1
return countpublic long countPairsWithin(int[] values, long limit) {
// [1] Start with one pointer at each end.
int left = 0;
int right = values.length - 1;
long count = 0; // 64-bit: 100,000 values have about 5 billion pairs
// [2] While two different values remain, compare their total with the limit.
while (left < right) {
// [3] It fits: values[left] fits with every value from left + 1 to right, so count them all.
if ((long) values[left] + values[right] <= limit) {
count += right - left;
left++;
}
// [4] Too large: values[right] fits with no value still in play, so rule it out.
else {
right--;
}
}
return count;
}long long countPairsWithin(const vector<int>& values, long long limit) {
// [1] Start with one pointer at each end.
int left = 0;
int right = (int) values.size() - 1;
long long count = 0; // 64-bit: 100,000 values have about 5 billion pairs
// [2] While two different values remain, compare their total with the limit.
while (left < right) {
// [3] It fits: values[left] fits with every value from left + 1 to right, so count them all.
if ((long long) values[left] + values[right] <= limit) {
count += right - left;
left++;
}
// [4] Too large: values[right] fits with no value still in play, so rule it out.
else {
right--;
}
}
return count;
}function countPairsWithin(values, limit) {
// [1] Start with one pointer at each end.
let left = 0;
let right = values.length - 1;
let count = 0; // exact up to 2^53, far above the 5 billion pairs of 100,000 values
// [2] While two different values remain, compare their total with the limit.
while (left < right) {
// [3] It fits: values[left] fits with every value from left + 1 to right, so count them all.
if (values[left] + values[right] <= limit) {
count += right - left;
left++;
}
// [4] Too large: values[right] fits with no value still in play, so rule it out.
else {
right--;
}
}
return count;
}Counting pairs within a limit: when the total fits, every value between left and right fits with left, so add them at once.
Exercise · Find the bug: The pair count that comes up short. This function counts the pairs of sorted prices whose total stays within a limit. It returns too few on some inputs. Which line is wrong?
def count_pairs_within(values, limit):
left = 0
right = len(values) - 1
count = 0
while left < right:
if values[left] + values[right] <= limit:
count += 1
left += 1
else:
right -= 1
return countA ride-hailing app wants to help a driver finish a shift on time. The driver has exactly 55 minutes left. The queued trips are sorted by estimated duration, in minutes: [6, 12, 24, 25, 30, 31, 33, 48]. Which two trips fill the 55 minutes exactly?
This is Template 1 with target = 55.
| Left | Right | Durations | Total | Compared with 55 | Move |
|---|---|---|---|---|---|
| 0 | 7 | 6 + 48 | 54 | too small | left moves to 1 |
| 1 | 7 | 12 + 48 | 60 | too large | right moves to 6 |
| 1 | 6 | 12 + 33 | 45 | too small | left moves to 2 |
| 2 | 6 | 24 + 33 | 57 | too large | right moves to 5 |
| 2 | 5 | 24 + 31 | 55 | exact | return [2, 5] |
The answer is [2, 5]: the 24-minute and the 31-minute trip. Two pairs fill 55 minutes here, 24 + 31 and 25 + 30. The template returns the one with the smaller left index, as the invariant promises.
Real production data brings edge cases.
A truck has 12 kg of room, and the list is [5, 9, 14, 22]. The totals are 27, then 19, then 14: all too heavy, so right moves in three times and meets left.
The template returns [-1, -1]. The loop always ends, because every step moves one pointer. Agree on this sentinel with the caller: -1 can never be a real index.
The list is [8, 29]. With 37 kg of room, the first comparison is exact, so the answer is [0, 1]. With 36 kg of room, the total is too heavy, right moves to 0, and the answer is [-1, -1].
Either way the loop runs once. Check that your code does not read past either end.
Some hubs list weights that repeat: [6, 9, 9, 14]. With 18 kg of room, the answer is [1, 2]: two different parcels that both weigh 9 kg.
With 12 kg of room, the answer is [-1, -1]. There is only one 6 kg parcel, and a parcel cannot be paired with itself. The pointers meet on index 0, and left < right stops the loop before 6 + 6 is tried.
The list [12] has right = 0 at the start, so the loop never runs, and the answer is [-1, -1]. An empty list has right = −1, and the same thing happens. No special case is needed, but test both.
Exercise · Break it: Find the input this count gets wrong. This function counts the pairs of sorted prices whose total is within the limit, but it compares with the wrong operator. Find an input where it gives the wrong count.
def count_pairs_within(values, limit):
left = 0
right = len(values) - 1
count = 0
while left < right:
if values[left] + values[right] < limit:
count += right - left
left += 1
else:
right -= 1
return countThis version moves right when the total is too small, and left when it is too large:
if total < target:
right -= 1 # bug: a total that is too small rules out left, not right
else:
left += 1Counterexample: the test list [4, 7, 11, 15, 20, 26, 31] with 37 kg of room. The bug returns [-1, -1]. The correct answer is [2, 5].
The first total, 35, is too small, so the bug drops the 31 kg parcel. Moving right only makes the total smaller, so every later total is too small too: 30, 24, 19, 15 and 11. The bug drops the 26 kg parcel on the way, and the pair is gone.
Moving the wrong pointer drops a value that still has a partner, and the search wrongly says no pair exists.
This version loops while left <= right.
Counterexample: [5, 9, 14] with 18 kg of room. The bug returns [1, 1]. The correct answer is [-1, -1].
The totals 19 and 14 move both pointers onto index 1. Then the loop runs once more and adds the 9 kg parcel to itself: 9 + 9 = 18. One parcel cannot fill the truck twice, so stop when the pointers meet.
A new hub sends its parcels in arrival order: [15, 4, 26, 31, 11, 7, 20], with 37 kg of room.
Counterexample: the template returns [-1, -1] on this list. But 26 + 11 = 37, so the correct answer is [2, 4].
The third total is 26 + 20 = 46, so right moves in to the 7 kg parcel. The next total is 26 + 7 = 33, and the template rules out 26 as too light. But 7 is not the heaviest parcel still in play; 31 is. The ruling-out argument needs sorted values, so sort first or use a hash map.
Your team lead brings a request from the loading team. Their scanner lists parcels in arrival order, [15, 4, 26, 31, 11, 7, 20], and loaders need the scanner positions of two parcels that fill 37 kg.
Sorting would move the parcels and lose their positions. You could carry each position along while you sort, but that costs O(n log n). A hash map from Module 3 is simpler: walk the list once and keep each weight with its position. At position 4, the weight 11 finds its complement 26, seen at position 2, so the answer is [2, 4].
That is O(n) time and O(n) memory, and the list order does not matter. This is LeetCode 1: Two Sum. Without sorted values, the opposite-ends argument has nothing to stand on.
Your team lead brings five product changes. Each one keeps the two pointers that rule out a value at every step.
An online store suggests two gifts whose prices together stay within a budget. Merchandising wants the number of pairs that fit. For the sorted prices [15, 25, 40, 60, 70] and a budget of 85, the answer is 6.
This is Template 2. The catalogue is stored in no particular order, so sort it first. It is the second practice problem.
A parcel-delivery app cargo bikes carry at most two parcels within a load limit. Dispatch wants the fewest bikes for a round. For the parcels [3, 5, 6, 8, 9] kg and a limit of 12 kg, the answer is 3 bikes: 9 with 3, then 8 alone, then 6 with 5.
Sort, then send the heaviest parcel on every bike, and add the lightest one when it fits. The heaviest parcel must ride anyway, and the lightest is its best partner. It is the third practice problem.
A bank app checks whether a statement reference code reads the same from both ends, ignoring separators and case. The code Ab-12-21-bA does: its letters and digits read ab1221ba both ways.
Put one pointer at each end, skip the separators, and compare the two characters. A match moves both pointers in; a mismatch means no. This is a checkpoint problem at the end of this stretch (LeetCode 125: Valid Palindrome).
A monitoring system stores each server's clock drift, sorted from the most negative to the most positive: [-7, -3, 0, 2, 5]. On-call wants the squares in sorted order: [0, 4, 9, 25, 49].
The largest square is always at one of the two ends, so compare the ends and write the larger square from the back of the output. Here the loop runs while left <= right, because every drift, even the last one, gets a square. This is the other checkpoint problem (LeetCode 977: Squares of a Sorted Array).
A pallet takes three parcels, and the planner wants the three whose total is closest to the pallet limit. For [4, 9, 13, 20, 26] kg and a limit of 47 kg, the best is 9 + 13 + 26 = 48 kg.
Fix the first parcel, then run two pointers on the parcels after it. That costs O(n^2) instead of O(n^3). You build this in the 3-sum concept later in this module (LeetCode 16: 3Sum Closest).
Game: pointer dance. Coming to the map as a side path.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate why each comparison can rule out a value for good, and why the pass is O(n). 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.
The list is sorted, so I put one pointer at each end and compare the total of the two values with the target.
Too small means the left value fails even with the largest one still in play, so left moves in. Too large means right moves in.
Each comparison rules out one value for good, so there are at most n minus 1 steps, and I stop when the pointers meet.
The values are sorted and the question asks for a pair, so I would use two pointers from opposite ends. The first attempt checks every pair. That is O(n^2): about 1.25 billion checks for 50,000 values.
Instead, I put left on the smallest value and right on the largest. Then I compare their total with the target. If it is too small, the value at left cannot reach the target even with the largest value still in play, so left moves in. If it is too large, the value at right is ruled out, so right moves in.
Each step rules out one value for good, so the pass is O(n) time with O(1) extra space.
I loop while left is less than right, so a value is never paired with itself. If the input is not sorted, I sort first for O(n log n). If I must return the original positions, I use a hash map instead. I would test no pair, two values and repeated values.
Checkpoint · Spot the pattern
Q1/3 Which request is a job for two pointers from opposite ends?
Answer: B
"Sorted" and "two parcels that add up to" are the signals. The consecutive-stops question is a sliding window, which comes in Module 5.
Q2/3 Sorted weights [3, 8, 14, 19, 25], target 30. Left is on 3 and right is on 25. Which pointer moves?
Answer: A
28 is below 30. The value at left cannot reach 30 even with 25, the largest value still in play, so left moves in. Only an exact total ends the search.
Q3/3 The total of the values at left and right is too large. Why can the value at right never be part of the answer?
Answer: B
All values in play are at least the value at left. If the total is already too large with the smallest one, it is too large with every one. That is the "too heavy" case from See.
Checkpoint · Cost and correctness
Q1/4 How many comparisons does the opposite-ends pass make at most on n values?
Answer: C
Each comparison either returns or rules out one value for good, and the pointers stop when they meet. So there are at most n − 1 comparisons: O(n).
Q2/4 Which statement is the opposite-ends invariant?
Answer: B
The invariant from Shape: a value leaves left..right only when it has no partner. When the pointers meet, one value cannot make a pair, so there is no answer.
Q3/4 Why does the loop run while left < right and not while left <= right?
Answer: C
With [5, 9, 14] and target 18, the pointers meet on 9, and left <= right returns [1, 1] because 9 + 9 = 18. One parcel cannot be used twice.
Q4/4 You run the template on [15, 4, 26, 31, 11, 7, 20] with target 37. It returns [-1, -1], but 26 + 11 = 37. Why?
Answer: A
The template rules out 26 as too light when right is on 7, but 7 is not the heaviest value still in play. Sort first, or use a hash map.
Checkpoint · Limits and variations
Q1/3 The list is in arrival order, and the loaders need the original positions of two parcels that fill the truck. What is the best tool?
Answer: B
A hash map works in any order and keeps positions: O(n) time and O(n) memory. Indexes in a sorted copy are not the scanner positions. This is LeetCode 1: Two Sum.
Q2/3 Sorted prices [10, 20, 30, 45, 55, 80], limit 75. Left is on 10 and right is on 55, and 10 + 55 = 65 fits. How many pairs does Template 2 add in this step?
Answer: B
Left is at index 0 and right at index 4. The value 10 fits with every value from index 1 to 4, so the step adds right − left = 4 pairs.
Q3/3 The values are not sorted, so you sort them before the opposite-ends pass. What is the total time?
Answer: B
Sorting costs O(n log n), and the pass costs O(n). The larger part wins, so the whole solution is O(n log n).
Ten questions on this lesson. Pass with 80% or more to open the gate to the next stretch on the Academy map.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Two parcels for the spare capacity | Freight | Easy | Template 1: an exact pair, the smallest first index, [-1, -1] |
| 2 | Gift pairs within the budget | Shop | Medium | Sort first, then Template 2: add right − left, 64-bit counts |
| 3 | Fewest cargo bikes for the round | Freight | Medium | Sort, then pair the heaviest parcel with the lightest |
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.