04
Partition / Dutch National Flag (Two Pointers Sub-pattern)
Rearrange elements into a few fixed groups in place. Each finished group grows behind its own pointer.
Signals in the problem statement
- ›
"sort an array of 0s, 1s and 2s"
- ›
"evens before odds"
- ›
"less than / equal / greater than pivot"
What makes it different
Not a search — a rearrangement. Think in regions (done-left, unknown-middle, done-right) and keep them correct after every swap.
Questions
ordered from “learn the idea” to “recognise it without help”- 1Sort Array By ParityWalkthroughEasyBasic Anchor·LeetCode #905
- 2Sort ColorsWalkthroughMediumBasic Reinforcement·LeetCode #75
- 3Partition Array According to Given PivotWalkthroughMediumTricky / Edge Case·LeetCode #2161
Template
partition-template.cpp
// Dutch National Flag: sort 0s, 1s and 2s in one pass.
// [0 .. low-1] = 0s, [low .. mid-1] = 1s, [mid .. high] = unknown, [high+1 .. n-1] = 2s
void dutchFlag(vector<int>& a) {
int low = 0, mid = 0, high = (int)a.size() - 1;
while (mid <= high) {
if (a[mid] == 0) swap(a[low++], a[mid++]); // a 0 joins the left region
else if (a[mid] == 1) mid++; // a 1 is already in place
else swap(a[mid], a[high--]); // a 2 joins the right region; don't move mid —
// the value swapped in hasn't been checked yet
}
}Remember this · Two Pointers
Trigger
Sorted array, pairs/triplets with a target, comparing from both ends, compacting an array in place.
Think
If I compare the elements at two positions, can I safely discard one side?
Key question
Which pointer moves, and why can the skipped elements never be the answer?