Learn the pattern · ~15 min
Cyclic Sort
also called index placement, array as hash
When the values are 1..n, value v has a home at index v − 1: swap every value home, and any index left holding the wrong value names a missing number.
Reach for it when you read
- +The values are 1..n or 0..n (or should be), so each value names an index.
- +Find the missing number, the duplicate, or both, in O(n) time and O(1) extra space.
- +"Smallest missing positive": only values 1..n matter, the rest are junk to skip.
- +You'd reach for a boolean "seen" array of size n, but extra memory isn't allowed.
Not this one when
- ×The array is read-only: no swaps, so use fast and slow pointers (or binary search on the value).
- ×Values go far beyond n, like up to 10⁹: no seat for them, so use a hash set or sort.
- ×You only need one missing number and the sum fits: n(n+1)/2 minus the sum, or XOR, is shorter.
Learn Cyclic Sort
First, what does "cyclic" mean here?
Cyclic sort only works on one kind of input: the values are 1..n (or 0..n), so every value names its own position. In a 5-element array, the value 3 belongs at index 2, the value 5 at index 4. Value v's home is index v − 1.
Take [3, 1, 5, 4, 2] and follow "where does this value belong?":
- index 0 holds 3, whose home is index 2
- index 2 holds 5, whose home is index 4
- index 4 holds 2, whose home is index 1
- index 1 holds 1, whose home is index 0, back where we started
That loop, 0 → 2 → 4 → 1 → 0, is a cycle. Index 3 holds 4, which is already home: a cycle of length one. Every array of 1..n splits into cycles like this, and the sort walks around each cycle with swaps until every value is home.
How do we put every value home?
The rule is one line:
Look at index i. If its value isn't home, swap it home and stay at i. If it is home, move on.
Why stay? Because the swap brought a new value to index i, and that one may not be home either.
| i | value at i | its home | what happens | array |
|---|---|---|---|---|
| 0 | 3 | 2 | not home: swap with index 2 | 5, 1, 3, 4, 2 |
| 0 | 5 | 4 | not home: swap with index 4 | 2, 1, 3, 4, 5 |
| 0 | 2 | 1 | not home: swap with index 1 | 1, 2, 3, 4, 5 |
| 0 | 1 | 0 | home: i++ | 1, 2, 3, 4, 5 |
| 1–4 | 2, 3, 4, 5 | 1–4 | each is home: i++ four times | 1, 2, 3, 4, 5 |
The three swaps at index 0 walk the cycle 0 → 2 → 4 → 1, putting 3, then 5, then 2 home (and the 1 lands home with the last swap). A cycle of four values takes three swaps.
The code for it
int i = 0;
while (i < n) {
int home = a[i] - 1;
if (a[i] != a[home]) swap(a[i], a[home]); // compare values, so a duplicate stops it
else i++;
}You don't need to memorise this. It's the table: is it home? no, swap it home and look again; yes, move on.
Why does the test compare values, a[i] != a[home], and not positions, i != home? When every value appears once, the two tests mean the same thing. With duplicates they don't, and that's next.
Fine, but how does this help us?
The classic problem: Find All Numbers Disappeared in an Array. There are n values, each between 1 and n, but some repeat, so some are missing. Return the missing ones. The catch: O(n) time and no extra space.
Take [4, 2, 6, 2, 1, 4] and solve it by hand. Check each number from 1 to 6:
| number | appears? |
|---|---|
| 1 | yes |
| 2 | yes, twice |
| 3 | no |
| 4 | yes, twice |
| 5 | no |
| 6 | yes |
The answer is [3, 5].
The brute force
What we did by hand: for every number from 1 to n, scan the array for it.
vector<int> missing;
for (int v = 1; v <= n; v++)
if (find(a.begin(), a.end(), v) == a.end()) missing.push_back(v);That's n scans of n elements, O(n²). For n = 10⁵ that's 10¹⁰ comparisons. Time limit exceeded. A seen array or hash set makes it O(n), but costs O(n) extra memory, which the problem forbids.
The one thought that fixes it
The array is the seen array. If every value goes home, then index j holds j + 1 exactly when the number j + 1 is in the array.
So what happens to a duplicate? Take the two 2s. The first 2 goes home to index 1. Later the second 2 shows up at some index i and wants index 1 too. But index 1 already holds a 2.
- If the test were
i != home, the second 2 would swap with the first 2. Nothing changes, so the loop sees the same 2 again and swaps again. Forever. On our array it gets stuck at index 0 on its very first duplicate. - With
a[i] != a[home], the loop sees that home already holds an equal value and moves on. The second 2 stays where it is.
And where does it stay? In a seat whose own number never arrived to claim it, which is a missing number's seat. So after seating, every index j that doesn't hold j + 1 names a missing number.
Seat everything with that loop, then read off:
vector<int> missing;
for (int j = 0; j < n; j++)
if (a[j] != j + 1) missing.push_back(j + 1);Dry run
Same array, [4, 2, 6, 2, 1, 4].
| i | value at i | its home | what happens | array |
|---|---|---|---|---|
| 0 | 4 | 3 | not home: swap | 2, 2, 6, 4, 1, 4 |
| 0 | 2 | 1 | index 1 holds a 2 already: duplicate, i++ | same |
| 1 | 2 | 1 | home, i++ | same |
| 2 | 6 | 5 | not home: swap | 2, 2, 4, 4, 1, 6 |
| 2 | 4 | 3 | index 3 holds a 4 already: duplicate, i++ | same |
| 3 | 4 | 3 | home, i++ | same |
| 4 | 1 | 0 | not home: swap | 1, 2, 4, 4, 2, 6 |
| 4 | 2 | 1 | duplicate, i++ | same |
| 5 | 6 | 5 | home, i++ | same |
Index 2 holds 4 instead of 3, and index 4 holds 2 instead of 5. The answer is [3, 5], the same as the brute force.
Why it's O(n)
There's no for with a nested loop here, but i sometimes stays put, so count differently. Every swap puts one value home for good: it's never moved again, because nothing swaps away a value that's already home. So there are at most n swaps. Every other step is an i++, and there are n of those. That's at most 2n steps: O(n) time, and the only extra memory is i and home: O(1) space.
From O(n²) down to O(n), by using the array's own positions as the "seen" marks.
Values 0..n? Missing Number
In Missing Number the values are 0..n with one missing, in an array of length n. The home of v is index v now, and the value n has no home at all, so skip it.
if (a[i] < n && a[i] != a[a[i]]) swap(a[i], a[a[i]]);
else i++;The first index j that doesn't hold j is the answer; if every index is right, the answer is n. [3, 0, 1] seats to [0, 1, 3]: index 2 holds 3, so 2 is missing. [4, 2, 0, 1, 3] seats to [0, 1, 2, 3, 4]: nothing is wrong, so the answer is 5.
One duplicate and one missing? Set Mismatch
Same seating. Now there's exactly one wrong index: the value sitting there is the duplicate, and j + 1 is the missing number. [1, 2, 2, 4] has index 2 holding 2: duplicate 2, missing 3.
Collect the duplicates instead
Find All Duplicates in an Array is the same seating with a different read-off: from each wrong index, collect the value a[j] instead of j + 1. Our array gives [4, 2].
Junk values mixed in? First Missing Positive
Now the values can be anything: 0, negatives, numbers far above n. Only values in 1..n have a home. Skip the rest before reading a[home], or you index out of bounds.
if (a[i] >= 1 && a[i] <= n && a[i] != a[a[i] - 1]) swap(a[i], a[a[i] - 1]);
else i++;The first index j not holding j + 1 gives the answer j + 1, or n + 1 if all are right. [3, 4, −1, 1] seats to [1, −1, 3, 4]: index 1 is wrong, so the answer is 2.
Remember this
- Values tied to positions (1..n or 0..n) and O(1) extra space: cyclic sort.
- After a swap, don't move
i: a new value just arrived. - Test
a[i] != a[home], noti != home. The value test is what stops duplicates from swapping forever. - Skip zeros, negatives and values above n before reading
a[home]. - Whenever a problem asks "which numbers from 1 to n are missing or repeated, without extra memory?", it's this. If the array is read-only, it isn't: use fast and slow pointers.
Practise it on Missing Number (values 0..n), then Find All Numbers Disappeared in an Array, Set Mismatch (one wrong seat, two answers), Find All Duplicates in an Array (collect the values), First Missing Positive (junk values) and Find the Duplicate Number (read-only: fast and slow pointers).
Below, watch Find All Numbers Disappeared in an Array run line by line.
Watch it work, line by line
Find All Numbers Disappeared in an Array ↗, nums = [4, 3, 2, 7, 8, 2, 3, 1] → [5, 6]. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Are the values 1..n (or 0..n) for an array of size n, and am I allowed to rearrange the array?
Reach for it when
- +values in range 1..n or 0..n
- +find missing / duplicate / first missing positive
- +O(1) extra space and O(n) time required
- +values bounded by n
- +array may be modified
It fails when
- ×The array is read-onlyuse Floyd cycle detection or binary search on value
- ×Values aren't bounded by n, so they have no home indexuse Hash set or sorting
- ×You must preserve the original orderuse Hash set / counting array
Looks like it, isn't (and the other way round)
- Find the Duplicate Number looks like Cyclic Sort, needs Fast & Slow Pointers
Array must not be modified and O(1) space: values form a functional graph whose cycle entry is the duplicate.
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1Why is the nested-looking loop O(n), not O(n²)?Reveal
Each swap puts one value home for good, and home values never move again. So there are at most n swaps plus n steps of i.
2Why compare
a[i] != a[a[i] - 1]and noti != a[i] - 1?RevealThe index check loops forever on a duplicate: two equal values keep swapping. Comparing values stops when the home already holds a copy.
3When can't you use cyclic sort?Reveal
When values aren't bounded by n, or the array is read-only. Then use a hash set, or fast and slow pointers for the duplicate.
Practice ladder
Finished Cyclic Sort? Mark it done and Lessgo moves you to the next step.