Cyclic Sort
O(n) / O(1)
Each value's correct index is the value itself — swap numbers home in one pass, then scan for the one out of place.
0%
mastery
0/6 solved
0/6 solved
Recognise it
The signal
n numbers in range 1..n (or 0..n); find the missing, duplicate, or first missing positive in O(n) time and O(1) space.
1Brute force
Sort O(n log n) or use a hash set O(n) extra space.
2The observation
Extra space or sorting: the array itself is used as the hash table because value v has a home at index v-1.
3Why it works
Value v belongs at index v-1; after the pass, index i holds i+1 unless i+1 is absent from the array.
Reach for it when
- +find missing / duplicate / first missing positive
- +O(1) extra space and O(n) time required
Not 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
Practice
0/6 solved
- Missing NumberFoundationFoundationAmazon, AdobeEasy
- Find All Numbers Disappeared in an ArrayApply it · Several missing values.Apply itEasy
- Set MismatchOne change · One duplicate and one missing at once.One changeEasy
- Find All Duplicates in an ArrayOne change · Report every value appearing twice.One changeMedium
- Find the Duplicate NumberTwists · Array is read-only, so swapping is not allowed.TwistsMedium
- First Missing PositiveMastery checkMastery checkAmazon, StripeHard
Pitfalls
Classic bugs
- !Thinking the inner swap loop makes it O(n²): each swap puts one value home for good, so total swaps are at most n.
Looks like it, isn't
- Find the Duplicate Number needs Fast & Slow Pointers
Why
Array must not be modified and O(1) space: values form a functional graph whose cycle entry is the duplicate. source ↗