Here’s a special array: it holds the numbers 1..n, each exactly once, just scrambled. That constraint is a gift — value v has a known address, index v-1. So skip comparisons entirely: pick up whatever’s under your pointer and swap it straight to where it belongs, over and over, until the slot is right. Every number walks home in O(n).
O(n) time · O(1) space · no comparisons · in-place
the constraint
Values are 1..n — so each has one correct index.
home index
Value v belongs at index v−1.
swap, don’t step
If the current value isn’t home, swap it there; only advance when it is.
anomaly finder
After sorting, any slot with the wrong value flags a missing or duplicate number.
cyclic_sort.js — swap each value home
Ready
An array of 1..n, scrambled. A pointer i sits at index 0. Press Step: if arr[i] isn’t already home (at index arr[i]−1), swap it there; if it is, advance the pointer.
0
pointer i
0
swaps
0
home
How it works
Ordinary sorts compare elements to decide order. Cyclic sort doesn’t need to — the value is the address. Standing at index i, you ask one question: is arr[i] already at its home index arr[i]−1? If not, swap it there (which drops whatever was there into your hand to deal with next). If yes, this slot is settled — step forward.
1
Look at the home index
For arr[i] = v, its home is v−1. Check what’s sitting there.
2
Not home → swap it home
Swap arr[i] with arr[v−1]. Now v is placed forever; you hold whatever it displaced. Don’t move the pointer — inspect the new arrival.
3
Already home → advance
If arr[i] is already at its correct index, step the pointer to i+1.
✓
Each swap settles one value
An element never leaves a correct slot, so ≤ n swaps total — the whole thing is O(n), comparison-free.
Time
O(n)
Space
O(1)
Comparisons
0
Swaps
≤ n
The code, and why it matters
# sort an array of 1..n in place, O(n), no comparisonsdef cyclic_sort(a):
i = 0
while i < len(a):
home = a[i] - 1 # value v belongs at index v-1if a[i] != a[home]: # not home (and not a duplicate)
a[i], a[home] = a[home], a[i]
else:
i += 1
return a
# find the missing number: after sorting, the first index i# where a[i] != i+1 is missing. Duplicates: a[i] != i+1 too.
The real payoff isn’t sorting — it’s the anomaly detection it unlocks. Once every present value is home, any index whose value doesn’t match instantly reveals the missing number, the duplicate, or the first missing positive — all in O(n) time and O(1) space. That family of interview problems is cyclic sort wearing different hats.
Quick check
1. Why doesn’t the pointer advance after a swap?
Right — swapping home sends the current value to its slot but pulls back whatever lived there. The pointer stays to deal with that new arrival.
2. Why is cyclic sort O(n) despite swapping inside the loop?
A settled element never moves again, and there are n slots, so at most n swaps happen across the whole run. Plus n pointer advances — O(n) total.
FAQ
What is cyclic sort?
An O(n), comparison-free way to sort an array holding the numbers 1..n, by swapping each value to its home index (value v → index v−1) until every slot is right.
What problems does it solve?
Find the missing number, find the duplicate, find all disappeared numbers, find the first missing positive, find the corrupt pair. After cyclic-sorting, mismatched slots reveal the anomalies in O(1) space.
Does it handle duplicates?
Yes — when the current value already equals the value at its target index, swapping can’t make progress, so the pointer advances. That stuck-at-a-duplicate slot is exactly how you detect the duplicate.
Isn’t this just counting sort?
They share the "value is the index" idea, but counting sort builds a separate count/output array (O(n) extra space). Cyclic sort works in place with swaps and O(1) space — and its byproduct is the anomaly detection counting sort doesn’t give you for free.
The picture: one slot, six swaps, seven homes
The page’s seven-element preset. The pointer never leaves index 0 until the value there is 1. Each swap sends the held value to index v − 1 and pulls in whatever was waiting there, so the arrows are six permanent placements out of seven.
Worked example, step by step
Take A = [7, 3, 1, 6, 2, 5, 4]. The loop reads j = A[i] − 1, the home of the value at i. If A[i] ≠ A[j] it swaps them and stays on i; otherwise it advances.
Step
i
A[i]
Home j
Action
Array after
1
0
7
6
swap A[0], A[6]
[4, 3, 1, 6, 2, 5, 7]
2
0
4
3
swap A[0], A[3]
[6, 3, 1, 4, 2, 5, 7]
3
0
6
5
swap A[0], A[5]
[5, 3, 1, 4, 2, 6, 7]
4
0
5
4
swap A[0], A[4]
[2, 3, 1, 4, 5, 6, 7]
5
0
2
1
swap A[0], A[1]
[3, 2, 1, 4, 5, 6, 7]
6
0
3
2
swap A[0], A[2]
[1, 2, 3, 4, 5, 6, 7]
7
0 to 6
1 to 7
i
already home: advance 7 times
[1, 2, 3, 4, 5, 6, 7]
Six swaps for seven elements: every swap puts one value in its final place, and the last value arrives free because it is all that is left. The array is one long cycle (0 → 6 → 3 → 5 → 4 → 1 → 2 → 0), which is why one slot did all the work. A permutation made of several shorter cycles would have the pointer settle at index 0, advance, and start a new chain at the next out-of-place slot. Now feed it a duplicate: [3, 1, 3, 4, 2] takes 2 swaps and ends as [1, 2, 3, 4, 3]. Index 4 holds 3 but belongs to 5, so the single index where A[i] ≠ i + 1 names the duplicate (3) and, by its index, the missing number (5).
Complexity and trade-offs
Case
Time
Space
Why
Cyclic sort
O(n)
O(1)
At most n − 1 swaps and n advances. Requires values in a known range 1..n.
Comparison sort (merge, quick, heap)
O(n log n)
O(1) to O(n)
Works on any values, but cannot beat n log n comparisons in general.
Counting sort
O(n + k)
O(k)
Also linear for a bounded range, but needs a second array of size k.
Hash set for “find the missing”
O(n)
O(n)
Simple and does not touch the input; costs a table the size of the data.
Sum or XOR trick
O(n)
O(1)
Finds one missing number without mutation, but cannot report several anomalies at once.
The inner swap makes the loop look quadratic, but the count of swaps is bounded globally: each swap fixes one value for good, so there are at most n of them across the whole run. What you give up is the input: cyclic sort rearranges it in place, which is a problem if the caller needs the original order, and the whole idea collapses if values can fall outside 1..n without a range check. For “find the duplicate” where mutation is forbidden, Floyd’s cycle detection reaches the same O(n) time and O(1) space on a read-only array.
Common mistakes
Advancing i after every swap
A for loop that swaps once per index leaves the incoming value unplaced. On [7, 3, 1, 6, 2, 5, 4] it finishes with [4, 2, 3, 5, 1, 6, 7], not sorted. Use a while loop that only advances when the element at i is home or is a duplicate.
Testing A[i] ≠ i + 1 instead of A[i] ≠ A[j]
With a duplicate, the value at its home slot is the same value, so swapping changes nothing and the test stays true. [3, 1, 3, 4, 2] at i = 0 swaps index 0 with index 2 (both 3) forever. Compare against the target slot, not against i + 1.
Tuple-swapping with a self-referencing index
In Python, A[i], A[A[i] − 1] = A[A[i] − 1], A[i] assigns A[i] first, so the second index is computed from the new value. On [3, 1, 2] it produces [2, 3, 2] and loses the 1. Compute j = A[i] − 1 into a variable first.
Skipping the range check
For “first missing positive”, inputs include 0, negatives and values above n. Using such a value as A[v − 1] is an out-of-bounds read or a write into the wrong slot. Only swap when 1 ≤ A[i] ≤ n.
Off-by-one on the home index
For values 1..n the home is v − 1. Using v works until the value n appears, then reads index n, one past the end. For values 0..n−1 the home is v itself; mixing the two conventions is the usual cause.
Where this shows up
Interview problems
“Missing Number”, “Find the Duplicate Number”, “Find All Numbers Disappeared in an Array”, “Set Mismatch” and “First Missing Positive” are all one scan of cyclic sort followed by a check for the slots that are not home.
Applying a permutation in place
Reordering an array by a permutation, such as an argsort result, without a second array follows the same cycle-walk: take a slot, send its element home, repeat until the chain closes, and move on to the next unvisited slot.
Sequence-number gaps
Dense identifiers, such as packet sequence numbers in a window or row ids in a block, can be placed into slots by value. The slots left holding the wrong number are exactly the lost or duplicated ones.
SOLVE IT YOURSELF
Solve it: sort 1…n by putting each value home
When the values are exactly 1…n, you do not need comparisons at all — every value already knows which index it belongs at. Write it in Python or TypeScript, running for real in your browser.
YOUR TASK
Implement cyclic_sort(nums): given a list containing the numbers 1…n in any order, return it sorted — in O(n), using swaps only, no comparison sort and no extra array.
HINTS — 5 IDEAS
The key fact: value v belongs at index v − 1. That is the whole algorithm.
Walk an index i. If nums[i] is not home, swap it to where it belongs — and do not advance i.
Only advance i once the value sitting at i is already correct. Each swap places at least one value permanently, so the total work is O(n) despite the nested feel.
Advancing after every swap is the classic bug: the value you just swapped in has not been checked.
Compare against nums[target] rather than against i + 1 — that form also terminates cleanly if duplicates ever appear, instead of looping forever.