Split values into less, equal and greater in one pass.
Use it when values fall into three groups and must be grouped in place, in one pass. Signal words: three groups, three classes, less, equal and greater, around a pivot, colours, group but not sort.
Start low and mid on the first index, high on the last.
Step look at the value at mid. Front group: swap with low, move low and mid on. Middle group: move mid on. Back group: swap with high, move high back, and leave mid where it is.
Stop when mid passes high. Loop while mid <= high, so the last unknown value is checked.
Around a pivot less than the pivot is the front group, equal is the middle and greater is the back. This is the partition step of quickselect and of quicksort with many repeats.
It does not keep equal values in their input order. If order matters, use a second array.
Cost: each step shrinks the unknown region by one, so exactly n steps: O(n) time, one pass, O(1) extra space.
In this lesson you learn to split an array into three groups in place, in one pass. Three pointers grow one group from the front and one from the back, and the middle group collects between them.
At a delivery hub, parcels wait on a loading belt before the trucks take them. Every parcel has a priority class: 0 for express, 1 for standard and 2 for economy. Your team lead sets the requirement for the belt controller.
Your team lead says: Before loading, the belt must be grouped: every express parcel first, then standard, then economy.
Trucks load after one full turn of the belt, so the controller gets one pass and memory for a few counters only.
The controller has a swap arm that can exchange any two parcels on the belt. Here is one short test belt, by class: [1, 2, 0, 1, 2, 0, 0, 1]. Grouped, it reads [0, 0, 0, 1, 1, 1, 2, 2].
So the task is this: regroup the belt in place, in one pass, with a few counters of memory.
Picture a row of cards dealt face down on a table. Each card is red, white or blue. You want the reds on the left, the whites in the middle and the blues on the right, and you may not start a second row.
You keep three markers. Low shows where the next red goes. Mid shows the next card to turn over. High shows where the next blue goes, counting from the right end.
Turn over the card at mid. A red swaps with the card at low, and both markers move right. A white stays, and mid moves right. A blue swaps with the face-down card at high, and high moves left.
After a blue, the card you get back is still face down, so you turn it over next. The face-down cards between mid and high are the unknown part, and every turn makes it one card shorter. Low, mid and high are the three pointers of this lesson.
Sorting cards of three colours in one pass: red to the left end, blue to the right end, white stays in the middle.
Before you write code, group the test belt by hand. It takes two minutes, and it shows you where the work goes.
Solve it by hand: The test belt by hand: express, then standard, then economy. The hand-solve sheet loads in your browser.
You work through it on the whiteboard. You read the belt once and count each class. Then you write the classes back: all the 0s, then the 1s, then the 2s.
Input: [1, 2, 0, 1, 2, 0, 0, 1].
| Position | Class | Express so far | Standard so far | Economy so far |
|---|---|---|---|---|
| 0 | 1 | 0 | 1 | 0 |
| 1 | 2 | 0 | 1 | 1 |
| 2 | 0 | 1 | 1 | 1 |
| 3 | 1 | 1 | 2 | 1 |
| 4 | 2 | 1 | 2 | 2 |
| 5 | 0 | 2 | 2 | 2 |
| 6 | 0 | 3 | 2 | 2 |
| 7 | 1 | 3 | 3 | 2 |
After the first pass, the counts are 3 express, 3 standard and 2 economy. In a second pass, You write three 0s, three 1s and two 2s: [0, 0, 0, 1, 1, 1, 2, 2].
Look at when the first class is written. You read the whole belt before you write anything, so you visit every position twice.
Remember this. You will use it soon.
You turn the hand method into code.
Start with a correct version. Count each class in one pass, then write the classes back in a second pass.
def group_by_count(classes):
counts = [0, 0, 0]
for c in classes: # pass 1: count each class
counts[c] += 1
i = 0
for cls in range(3): # pass 2: write each class back, in order
for _ in range(counts[cls]):
classes[i] = cls
i += 1
return classesThis is correct, and it is fast. It makes two passes of n steps, so it is O(n), with three counters of memory. For the test belt it makes 16 steps. The team keeps it as the reference: every faster version must give the same answers.
A library sort also gives the right answer. But it costs O(n log n), and many library sorts need a second array. The controller has memory for a few counters only.
Now check the real belts.
At the central hubs, a belt holds 3,000 parcels, and one full turn of the belt takes 6 minutes.
Here is the count for one belt:
So the problem is not the number of operations. The controller computes fast. The belt is what takes time, and the first attempt needs it twice.
Predict the cost
Q One full turn of the belt takes 6 minutes, and each pass over the belt is one turn. How long does the first attempt take to group a belt of 3,000 parcels?
Answer: C
The 6,000 steps take about 60 microseconds of computing, but the count pass and the write pass are two full turns: 2 × 6 = 12 minutes. Trucks load after 6 minutes, so the first attempt takes twice the budget.
The first attempt is correct, and its code is fast. But it needs two turns of the belt, and the trucks wait for both. Now the team looks for the pass it can remove.
Look at the counts on the whiteboard.
Express always starts at the front, and economy always ends at the back. Why count first? Can we do better?
The first attempt counts only to learn where each block starts. But two of the blocks have a fixed place. Express parcels always go at the front, and economy parcels always go at the back.
So do not count. Grow the express block from the front and the economy block from the back while you read. Standard parcels collect in the middle on their own.
You need three indexes:
The positions from mid to high hold parcels that nobody has checked yet. This part is the unknown region.
| Before low | Low to mid − 1 | Mid to high | After high |
|---|---|---|---|
| 0, express | 1, standard | unknown | 2, economy |
At each step, look at the parcel at mid:
Each step moves mid forward or high back, so the unknown region shrinks by exactly one parcel. When mid passes high, nothing is unknown, and the belt is grouped. Every parcel is checked once, so this is one pass.
Splitting values into three groups like this is called a three-way partition. This method for it is known as the Dutch national flag, after a flag with three stripes: red, white and blue, like the cards in the analogy.
| Step | Low, mid, high before | Class at mid | What happens | Came back to mid | Low, mid, high after | Belt after |
|---|---|---|---|---|---|---|
| 1 | 0, 0, 7 | 1 | 1: mid moves on | none | 0, 1, 7 | 1, 2, 0, 1, 2, 0, 0, 1 |
| 2 | 0, 1, 7 | 2 | 2: swap with index 7, high moves back | 1 | 0, 1, 6 | 1, 1, 0, 1, 2, 0, 0, 2 |
| 3 | 0, 1, 6 | 1 | 1: mid moves on | none | 0, 2, 6 | 1, 1, 0, 1, 2, 0, 0, 2 |
| 4 | 0, 2, 6 | 0 | 0: swap with index 0, low and mid move on | 1 | 1, 3, 6 | 0, 1, 1, 1, 2, 0, 0, 2 |
| 5 | 1, 3, 6 | 1 | 1: mid moves on | none | 1, 4, 6 | 0, 1, 1, 1, 2, 0, 0, 2 |
| 6 | 1, 4, 6 | 2 | 2: swap with index 6, high moves back | 0 | 1, 4, 5 | 0, 1, 1, 1, 0, 0, 2, 2 |
| 7 | 1, 4, 5 | 0 | 0: swap with index 1, low and mid move on | 1 | 2, 5, 5 | 0, 0, 1, 1, 1, 0, 2, 2 |
| 8 | 2, 5, 5 | 0 | 0: swap with index 2, low and mid move on | 1 | 3, 6, 5 | 0, 0, 0, 1, 1, 1, 2, 2 |
The belt is grouped after 8 steps for 8 parcels, with 5 swaps. Look at step 6. The swap brings an express parcel back to index 4. Mid stays, so step 7 checks it and sends it to the express block.
Race: Count then write back, against the Dutch national flag. The operation counter loads in your browser.
The race counts the belt positions each version visits, on random belts. At 10,000 parcels, the first attempt visits 20,000 positions: every parcel twice. The Dutch national flag visits 10,000, every parcel once. For a hub belt of 3,000 parcels, that is one turn of 6 minutes instead of two.
The flag does not save every kind of work. On a seeded random belt of 3,000 parcels it makes 2,003 swaps, and each swap moves two parcels. The swaps happen inside the one turn, so the saving that matters is the second turn.
Three pointers split the belt into four regions: zeros, ones and twos that are settled, and an unknown middle still to check.
One pass: the parcel at mid goes to its region, and a swap with high leaves mid in place to check what came back.
A belt at a second hub reads [0, 2, 1, 2, 0, 1, 2]. The player stops at five steps and asks you to predict.
Dry run: Predict each step: a second belt. The step-by-step player loads in your browser.
Reading without the player? Cover the last three columns and predict them row by row.
| Step | Low, mid, high before | Class at mid | What happens | Came back to mid | Low, mid, high after | Belt after |
|---|---|---|---|---|---|---|
| 1 | 0, 0, 6 | 0 | 0: swap with index 0, low and mid move on | 0 | 1, 1, 6 | 0, 2, 1, 2, 0, 1, 2 |
| 2 | 1, 1, 6 | 2 | 2: swap with index 6, high moves back | 2 | 1, 1, 5 | 0, 2, 1, 2, 0, 1, 2 |
| 3 | 1, 1, 5 | 2 | 2: swap with index 5, high moves back | 1 | 1, 1, 4 | 0, 1, 1, 2, 0, 2, 2 |
| 4 | 1, 1, 4 | 1 | 1: mid moves on | none | 1, 2, 4 | 0, 1, 1, 2, 0, 2, 2 |
| 5 | 1, 2, 4 | 1 | 1: mid moves on | none | 1, 3, 4 | 0, 1, 1, 2, 0, 2, 2 |
| 6 | 1, 3, 4 | 2 | 2: swap with index 4, high moves back | 0 | 1, 3, 3 | 0, 1, 1, 0, 2, 2, 2 |
| 7 | 1, 3, 3 | 0 | 0: swap with index 1, low and mid move on | 1 | 2, 4, 3 | 0, 0, 1, 1, 2, 2, 2 |
Look at step 2. The swap with high brings back another economy parcel, so mid stays and checks it again in step 3. Step 7 runs while mid equals high: the last unknown parcel is express, and it still needs its swap.
Exercise · Predict the output: Where do low, mid and high end?. Express is 0, standard is 1 and economy is 2. What does this print after the loop ends?
values = [2, 0, 1, 2, 1, 1, 0]
low, mid, high = 0, 0, len(values) - 1
while mid <= high:
if values[mid] == 0:
values[low], values[mid] = values[mid], values[low]
low += 1
mid += 1
elif values[mid] == 1:
mid += 1
else:
values[mid], values[high] = values[high], values[mid]
high -= 1
print(low, mid, high)Here is the rule that keeps the pass correct. Every line of the templates below exists to protect it.
Every value before low is 0, from low to mid − 1 is 1, after high is 2, and mid to high is the unknown region.
At the start, low and mid are 0 and high is n − 1. The first three regions are empty, and everything is unknown, so the rule holds.
Now take one step. A 0 at mid swaps with the first 1 at low, so the 0 block and the 1 block each shift one slot right. A 1 at mid joins the end of the 1 block. A 2 at mid swaps into the slot at high and joins the 2 block, while an unchecked value takes its place in the unknown region.
In every case the rule still holds, and the unknown region is one value shorter. When mid passes high, the unknown region is empty, so the array holds the 0s, then the 1s, then the 2s.
Use it when values fall into three groups and must be grouped in place, in one pass. Signal words: three groups, three classes, less, equal and greater, around a pivot, colours, group but not sort.
Start: low and mid on the first index, high on the last.
Step: look at the value at mid. Front group: swap with low, move low and mid on. Middle group: move mid on. Back group: swap with high, move high back, and leave mid where it is.
Stop: when mid passes high. Loop while mid <= high, so the last unknown value is checked.
Around a pivot: less than the pivot is the front group, equal is the middle and greater is the back. This is the partition step of quickselect and of quicksort with many repeats.
It does not keep equal values in their input order. If order matters, use a second array.
Cost: each step shrinks the unknown region by one, so exactly n steps: O(n) time, one pass, O(1) extra space.
def dutch_flag(values):
# [1] Start: low and mid at the front, high at the back. Every value is unknown.
low = 0
mid = 0
high = len(values) - 1
# [2] While the unknown region mid..high is not empty, check the value at mid.
while mid <= high:
# [3] A 0: swap it to the end of the 0 block. The value from low is already checked, so both move on.
if values[mid] == 0:
values[low], values[mid] = values[mid], values[low]
low += 1
mid += 1
# [4] A 1: it already sits at the end of the 1 block, so mid moves on.
elif values[mid] == 1:
mid += 1
# [5] A 2: swap it to the front of the 2 block. The value from high is unchecked, so mid stays.
else:
values[mid], values[high] = values[high], values[mid]
high -= 1
# [6] The unknown region is empty: all 0s, then all 1s, then all 2s.
return valuespublic int[] dutchFlag(int[] values) {
// [1] Start: low and mid at the front, high at the back. Every value is unknown.
int low = 0;
int mid = 0;
int high = values.length - 1;
// [2] While the unknown region mid..high is not empty, check the value at mid.
while (mid <= high) {
// [3] A 0: swap it to the end of the 0 block. The value from low is already checked, so both move on.
if (values[mid] == 0) {
int moved = values[low];
values[low] = values[mid];
values[mid] = moved;
low++;
mid++;
}
// [4] A 1: it already sits at the end of the 1 block, so mid moves on.
else if (values[mid] == 1) {
mid++;
}
// [5] A 2: swap it to the front of the 2 block. The value from high is unchecked, so mid stays.
else {
int moved = values[high];
values[high] = values[mid];
values[mid] = moved;
high--;
}
}
// [6] The unknown region is empty: all 0s, then all 1s, then all 2s.
return values;
}vector<int> dutchFlag(vector<int>& values) {
// [1] Start: low and mid at the front, high at the back. Every value is unknown.
int low = 0;
int mid = 0;
int high = (int) values.size() - 1;
// [2] While the unknown region mid..high is not empty, check the value at mid.
while (mid <= high) {
// [3] A 0: swap it to the end of the 0 block. The value from low is already checked, so both move on.
if (values[mid] == 0) {
swap(values[low], values[mid]);
low++;
mid++;
}
// [4] A 1: it already sits at the end of the 1 block, so mid moves on.
else if (values[mid] == 1) {
mid++;
}
// [5] A 2: swap it to the front of the 2 block. The value from high is unchecked, so mid stays.
else {
swap(values[mid], values[high]);
high--;
}
}
// [6] The unknown region is empty: all 0s, then all 1s, then all 2s.
return values;
}function dutchFlag(values) {
// [1] Start: low and mid at the front, high at the back. Every value is unknown.
let low = 0;
let mid = 0;
let high = values.length - 1;
// [2] While the unknown region mid..high is not empty, check the value at mid.
while (mid <= high) {
// [3] A 0: swap it to the end of the 0 block. The value from low is already checked, so both move on.
if (values[mid] === 0) {
[values[low], values[mid]] = [values[mid], values[low]];
low++;
mid++;
}
// [4] A 1: it already sits at the end of the 1 block, so mid moves on.
else if (values[mid] === 1) {
mid++;
}
// [5] A 2: swap it to the front of the 2 block. The value from high is unchecked, so mid stays.
else {
[values[mid], values[high]] = [values[high], values[mid]];
high--;
}
}
// [6] The unknown region is empty: all 0s, then all 1s, then all 2s.
return values;
}Rebuild the template: put its lines back in order. Loads in your browser.
The values do not have to be 0, 1 and 2. Compare the value at mid with a pivot instead. Less than the pivot goes to the front, equal stays in the middle, and greater goes to the back. The pointers and the swaps stay the same.
The groups come out grouped, not sorted: the values below the pivot can be in any order. The order is still fixed for a given input, because the steps are fixed. The same input always gives the same output.
def partition_around(values, pivot):
# [1] Start: low and mid at the front, high at the back. Every value is unknown.
low = 0
mid = 0
high = len(values) - 1
# [2] While the unknown region mid..high is not empty, compare the value at mid with the pivot.
while mid <= high:
# [3] Less: swap it to the end of the less block. The value from low is already checked, so both move on.
if values[mid] < pivot:
values[low], values[mid] = values[mid], values[low]
low += 1
mid += 1
# [4] Equal: it already sits at the end of the equal block, so mid moves on.
elif values[mid] == pivot:
mid += 1
# [5] Greater: swap it to the front of the greater block. The value from high is unchecked, so mid stays.
else:
values[mid], values[high] = values[high], values[mid]
high -= 1
# [6] The unknown region is empty: less, then equal, then greater.
return valuespublic int[] partitionAround(int[] values, int pivot) {
// [1] Start: low and mid at the front, high at the back. Every value is unknown.
int low = 0;
int mid = 0;
int high = values.length - 1;
// [2] While the unknown region mid..high is not empty, compare the value at mid with the pivot.
while (mid <= high) {
// [3] Less: swap it to the end of the less block. The value from low is already checked, so both move on.
if (values[mid] < pivot) {
int moved = values[low];
values[low] = values[mid];
values[mid] = moved;
low++;
mid++;
}
// [4] Equal: it already sits at the end of the equal block, so mid moves on.
else if (values[mid] == pivot) {
mid++;
}
// [5] Greater: swap it to the front of the greater block. The value from high is unchecked, so mid stays.
else {
int moved = values[high];
values[high] = values[mid];
values[mid] = moved;
high--;
}
}
// [6] The unknown region is empty: less, then equal, then greater.
return values;
}vector<int> partitionAround(vector<int>& values, int pivot) {
// [1] Start: low and mid at the front, high at the back. Every value is unknown.
int low = 0;
int mid = 0;
int high = (int) values.size() - 1;
// [2] While the unknown region mid..high is not empty, compare the value at mid with the pivot.
while (mid <= high) {
// [3] Less: swap it to the end of the less block. The value from low is already checked, so both move on.
if (values[mid] < pivot) {
swap(values[low], values[mid]);
low++;
mid++;
}
// [4] Equal: it already sits at the end of the equal block, so mid moves on.
else if (values[mid] == pivot) {
mid++;
}
// [5] Greater: swap it to the front of the greater block. The value from high is unchecked, so mid stays.
else {
swap(values[mid], values[high]);
high--;
}
}
// [6] The unknown region is empty: less, then equal, then greater.
return values;
}function partitionAround(values, pivot) {
// [1] Start: low and mid at the front, high at the back. Every value is unknown.
let low = 0;
let mid = 0;
let high = values.length - 1;
// [2] While the unknown region mid..high is not empty, compare the value at mid with the pivot.
while (mid <= high) {
// [3] Less: swap it to the end of the less block. The value from low is already checked, so both move on.
if (values[mid] < pivot) {
[values[low], values[mid]] = [values[mid], values[low]];
low++;
mid++;
}
// [4] Equal: it already sits at the end of the equal block, so mid moves on.
else if (values[mid] === pivot) {
mid++;
}
// [5] Greater: swap it to the front of the greater block. The value from high is unchecked, so mid stays.
else {
[values[mid], values[high]] = [values[high], values[mid]];
high--;
}
}
// [6] The unknown region is empty: less, then equal, then greater.
return values;
}The Dutch national flag template, line by line: three pointers, one loop, and a swap for each class.
Exercise · Find the bug: The pivot that joins the wrong block. This function groups values into less than, equal to and greater than the pivot. Equal values end up mixed with the smaller ones. Which line is wrong?
def partition_around(values, pivot):
low, mid, high = 0, 0, len(values) - 1
while mid <= high:
if values[mid] <= pivot:
values[low], values[mid] = values[mid], values[low]
low += 1
mid += 1
elif values[mid] == pivot:
mid += 1
else:
values[mid], values[high] = values[high], values[mid]
high -= 1
return valuesA monitoring system checks one service against a response-time target of 200 ms. On-call wants the requests of the last batch grouped: faster than the target, then on target, then slower. The response times, in milliseconds, are [240, 180, 200, 310, 150, 200, 90, 260].
This is Template 2 with pivot = 200.
| Step | Low, mid, high before | Value at mid | What happens | Low, mid, high after | Array after |
|---|---|---|---|---|---|
| 1 | 0, 0, 7 | 240 | greater: swap with index 7 | 0, 0, 6 | 260, 180, 200, 310, 150, 200, 90, 240 |
| 2 | 0, 0, 6 | 260 | greater: swap with index 6 | 0, 0, 5 | 90, 180, 200, 310, 150, 200, 260, 240 |
| 3 | 0, 0, 5 | 90 | less: swap with index 0 | 1, 1, 5 | 90, 180, 200, 310, 150, 200, 260, 240 |
| 4 | 1, 1, 5 | 180 | less: swap with index 1 | 2, 2, 5 | 90, 180, 200, 310, 150, 200, 260, 240 |
| 5 | 2, 2, 5 | 200 | equal: mid moves on | 2, 3, 5 | 90, 180, 200, 310, 150, 200, 260, 240 |
| 6 | 2, 3, 5 | 310 | greater: swap with index 5 | 2, 3, 4 | 90, 180, 200, 200, 150, 310, 260, 240 |
| 7 | 2, 3, 4 | 200 | equal: mid moves on | 2, 4, 4 | 90, 180, 200, 200, 150, 310, 260, 240 |
| 8 | 2, 4, 4 | 150 | less: swap with index 2 | 3, 5, 4 | 90, 180, 150, 200, 200, 310, 260, 240 |
The answer is [90, 180, 150, 200, 200, 310, 260, 240]: three faster requests, two on target and three slower. The faster group is not sorted, because 150 comes after 180. Steps 1 and 2 show why mid stays after a swap with high: 260 came back to index 0 and was slower too.
Real production data brings edge cases.
A hub that ships only standard parcels sends [1, 1, 1, 1]. Mid walks to the end, and nothing is swapped.
A belt of economy parcels, [2, 2, 2], is different. Every step swaps a 2 with a 2 at high, and high moves back until it reaches −1. Mid never moves. Both belts come back unchanged, but check that your code accepts high = −1 at the end.
A late belt has no standard parcels: [2, 0, 0, 2, 0]. The standard block stays empty the whole time, so low always equals mid.
Each express parcel swaps with itself, and the answer is [0, 0, 0, 2, 2]. No special case is needed.
For [0] and for [2], low, mid and high all start on index 0. One step places the parcel, and the belt comes back unchanged. An empty belt has high = −1, so the loop never runs.
The belt [0, 0, 1, 2, 2] is already in order. The template still makes 5 steps and 4 swaps: each express parcel swaps with itself, and each economy parcel swaps with an equal one.
The answer is the input, unchanged. One pass is the cost even when there is no work to do.
Exercise · Break it: Find the input this partition leaves unsorted. This three-way partition around a pivot loops while mid < high. Find an input where its groups come out wrong.
def partition_around(values, pivot):
low, mid, high = 0, 0, len(values) - 1
while mid < high:
if values[mid] < pivot:
values[low], values[mid] = values[mid], values[low]
low += 1
mid += 1
elif values[mid] == pivot:
mid += 1
else:
values[mid], values[high] = values[high], values[mid]
high -= 1
return valuesThis version moves mid on after every step, including a swap with high:
else:
values[mid], values[high] = values[high], values[mid]
high -= 1
mid += 1 # bug: the value that came back from high has not been checkedCounterexample: the test belt [1, 2, 0, 1, 2, 0, 0, 1]. The bug returns [0, 0, 1, 1, 0, 1, 2, 2]. The correct answer is [0, 0, 0, 1, 1, 1, 2, 2].
When the economy parcel at index 4 swaps with index 6, an express parcel comes back to index 4. The bug moves mid to 5 without checking it, so the express parcel stays among the standard ones.
After swapping with high, mid must stay: the parcel that came back is unchecked, and moving on can leave a zero behind.
This version loops while mid < high.
Counterexample: [1, 1, 0]. The bug returns [1, 1, 0]. The correct answer is [0, 1, 1].
Mid moves past the two standard parcels and stops on index 2, where high also is. One parcel is still unknown, but mid < high is false, so the loop ends before it checks the express parcel. When mid equals high, the unknown region holds one value, so loop while mid <= high.
Each parcel also has a code, and the loading team wants parcels of one class to stay in arrival order. You run the flag on the classes and carries each code along.
Counterexample: parcels 301 to 305 with classes [2, 1, 0, 1, 0]. The flag returns the codes 305, 303, 302, 304, 301. Parcel 303 arrived before 305, but now it comes after it.
In the first step, the economy parcel 301 swaps with 305 at high. That one swap jumps 305 over 303. A partition that keeps equal values in their input order is a stable partition, and the Dutch national flag is not one. A stable partition needs an output list: count the groups, then copy each value to its group's next free slot.
Your team lead brings a request from the zone planners. Parcels for five delivery zones share one belt, with zones 0 to 4: [3, 0, 4, 1, 3, 2, 0]. They want zone 0 first and zone 4 last.
Three pointers give you two ends and one middle, so they make three groups only. There is no fourth region to grow. You could partition again inside the middle, but each extra partition is another pass.
For a few small keys, count each key and write the groups back. That is counting sort (Module 7), and it needs two passes. If each parcel carries a code, copy whole parcels to an output list instead of writing keys back.
Your team lead brings four product changes. Each one keeps the idea of growing groups from the two ends around a middle.
An ad platform shows the bids of one auction grouped around the reserve price: below, equal, then above. Reviewers read each group as a timeline, so bids must stay in arrival order. For the bids [70, 20, 50, 90, 50, 10] and a reserve of 50, the screen shows [20, 10, 50, 50, 70, 90].
The flag would break the timeline, as Exhibit 3 showed. Count the groups, then copy each bid to its group's next free slot: a stable partition with O(n) extra memory. It is the second practice problem (LeetCode 2161: Partition Array According to Given Pivot).
A ride-hailing app reports one pickup time per zone: the k-th fastest of the day. For the times [300, 120, 240, 120, 420] in seconds and k = 3, the answer is 240.
Pick a pivot, run Template 2, and look at where position k − 1 falls. If it falls in the equal block, the pivot is the answer; otherwise keep only the side that holds it. That is quickselect: O(n) on average. It is the third practice problem (LeetCode 215: Kth Largest Element in an Array).
An online store sorts a large catalogue by price, and many products share a price such as 499 or 999 units. A quicksort that splits into two groups keeps sorting the repeated prices again and again.
With Template 2 as its partition step, every copy of the pivot lands in the equal block and is never touched again. You build this in the Quick sort concept in Module 7.
A bank app lists accounts on a statement and wants zero-balance accounts moved to the end. The other accounts must keep their order. For the balances [0, 120, 0, 45, 300], the list becomes [120, 45, 300, 0, 0].
This has two groups, and one of them must keep its order. Read and write pointers from the last lesson do it: copy each non-zero balance to the write slot, then fill the rest with zeros (LeetCode 283: Move Zeroes).
Exercise · Put it in order: Zero balances to the end. Arrange the lines to move the zero balances to the end while the other balances keep their order.
def move_zeroes(values):
write = 0
for read in range(len(values)):
if values[read] != 0:
values[write] = values[read]
write += 1
for i in range(write, len(values)):
values[i] = 0
return values
values[read] = values[write]Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate why mid does not move after a swap with high, and why the pass takes exactly n steps. 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.
Low, mid and high keep four regions: 0s before low, 1s up to mid, unknown values from mid to high, and 2s after high.
A 0 swaps with low; both move on. A 1 moves mid on. A 2 swaps with high; mid stays, since that value is unchecked.
Each step shrinks the unknown region by one: exactly n steps, one pass, O(1) memory. But it is not stable.
The values fall into three groups, and I must group them in place in one pass, so I would use a three-way partition, the Dutch national flag. Counting each group and writing it back is correct and O(n), but it takes two passes.
I keep three pointers. Before low are the 0s, from low to mid minus 1 the 1s, after high the 2s, and mid to high is still unknown.
I look at the value at mid. A 0 swaps with low, and both move on. A 1 moves mid on. A 2 swaps with high, and high moves back, but mid stays, because the value that came back is unchecked.
Each step shrinks the unknown region by one, so it is exactly n steps: O(n) time and O(1) space. I loop while mid is at most high. It is not stable, so if order matters I use an output list. I would test one class, two classes and a single value.
Checkpoint · Read and write pointers
Q1/3 Template 1 from Read and write pointers removes every -1 from [-1, 73, -1, 46, 58]. At the end, the array holds [73, 46, 58, 46, 58] and write is 3. What do you return?
Answer: B
The kept prefix ends at slot write − 1. The slots after it still hold old values, so returning them repeats 46 and 58.
Q2/3 Why can the write pointer never overwrite a value that has not been read yet?
Answer: B
Both start at 0, and write moves only in a step where read also moves. So write is at read or behind it, and the slot it writes to has already been read.
Q3/3 This code walks forward, deletes each 0 with codes.pop(i), and always does i += 1. What does it return for [8, 0, 0, 5]?
Answer: B
After codes.pop(1), the second 0 slides into slot 1, but i moves on to slot 2, so that 0 is never checked. Deleting while you walk forward skips the value that slides in.
Checkpoint · Three pointers
Q1/4 Which request is a job for a three-way partition?
Answer: C
Three groups, in place, one pass: those are the signals. The pair is opposite ends, the removal is read and write pointers, and the run of stops is a sliding window.
Q2/4 The value at mid is a 2. What does the Dutch national flag do?
Answer: B
The value that comes back from high has not been checked yet, so mid must look at it next. Moving mid on is Exhibit 1 in the mistake museum.
Q3/4 An array of 9 values is in the middle of a Dutch national flag pass, with low = 2, mid = 4 and high = 6. Which indexes hold 1s?
Answer: B
From low to mid − 1 the values are 1. Before low are the 0s, mid to high is unknown, and after high are the 2s.
Q4/4 A version of the template loops while mid < high. What does it return for [0, 1, 0]?
Answer: A
Mid places the 0 and passes the 1, then stops on index 2, where high also is. One value is still unknown, but mid < high is false. Loop while mid <= high.
Checkpoint · Cost, limits and variations
Q1/3 How many steps does the Dutch national flag take on n values?
Answer: C
Each step moves mid forward or high back, so the unknown region loses one value per step. That is exactly n steps, in one pass, with O(1) extra memory.
Q2/3 Bids must be grouped below, at and above a reserve price, and inside each group they must keep their arrival order. What do you use?
Answer: B
The Dutch national flag is not stable: one swap can jump a value over others of its group, as Exhibit 3 showed. Keeping arrival order needs O(n) extra memory.
Q3/3 Template 2 runs on [50, 40, 10, 40, 30] with pivot 40. What does it return?
Answer: B
Less than 40, then equal, then greater. The groups are not sorted: 30 comes back from high in the first step and takes slot 0, so it stays before 10.
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 stretch on the Academy map. The two problems are "First use of each idempotency key" and "Typed queries with backspaces".
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Group parcels by priority class | Freight | Easy | Template 1: the Dutch national flag on 0, 1 and 2 |
| 2 | Bids around the reserve price | Ads | Medium | A stable three-way partition with an output list |
| 3 | The k-th fastest pickup | Rides | Medium | Template 2 inside quickselect, with many repeats |
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.