Cyclic sort
When the values are the numbers 0 to n or 1 to n, each value has a home index. Swap every value straight to its home. After one pass, the slots whose values are wrong show what is missing or repeated.
How to recognise it
- The array holds numbers in a known range such as 1 to n or 0 to n.
- Find the missing number, the repeated number, or both.
- O(n) time with O(1) extra memory is required.
- Each value can be read as an index, which links the array into chains and cycles.
The idea in one picture
A row of numbered lockers and a pile of numbered coats, one per locker. Pick up the coat at the first locker. If it is not this locker's coat, hang it in its own locker, and pick up the coat you displace. Keep going until the coat in your hand belongs here, then move to the next locker. Every swap sends one coat home for good, so the whole row is sorted with at most n swaps. If a coat is missing or doubled, the lockers that end up with the wrong coat say which.
Template: values 1 to n
i = 0
while i < n:
home = nums[i] - 1
if nums[i] is in range and nums[home] != nums[i]:
swap nums[i], nums[home] # stay on i: a new value just arrived
else:
i = i + 1
for j from 0 to n - 1:
if nums[j] != j + 1: slot j is the odd one out
The check nums[home] != nums[i] (not home != i) matters. If the home already holds a copy of the same value,
swapping would loop forever, so you move on instead.
A guided example: [3, 5, 4, 1, 1]
| i | value | its home | action | array |
|---|---|---|---|---|
| 0 | 3 | 2 | swap | [4, 5, 3, 1, 1] |
| 0 | 4 | 3 | swap | [1, 5, 3, 4, 1] |
| 0 | 1 | 0 | home, move on | [1, 5, 3, 4, 1] |
| 1 | 5 | 4 | swap | [1, 1, 3, 4, 5] |
| 1 | 1 | 0 | a copy is home, move on | [1, 1, 3, 4, 5] |
Index 1 holds 1 instead of 2: 2 is missing and 1 is repeated.
The same view without swapping
Reading each value as "go to this index" turns the array into chains of arrows. That view counts the swaps needed to sort any array (each cycle of length L needs L - 1 swaps). It also finds a repeated value without changing the array, with slow and fast pointers.
Common mistakes
- Moving
iforwards after a swap, which leaves the newly arrived value out of place. - Comparing
home != iinstead ofnums[home] != nums[i], which loops forever on repeated values. - Forgetting the home index shift: values 1 to n live at 0 to n - 1.
- Using cyclic sort when the problem forbids changing the input.
Problems
- Missing Numbereasyguide ready
- Find the repeating and missing numbermediumguide ready
- Find the Duplicate Numbermediumguide ready
- minimum no. of swaps required to sort the arraymediumguide ready