Array techniquesAnimated
Cyclic Sort
Put each value at the index it belongs to by swapping.
Time
O(n)
Extra space
O(1)
Use it for
Values in range 1..n; finding missing/duplicate numbers.
How it works
- If the values are exactly 1..n, value v belongs at index v − 1.
- Look at the item at index i. If it is not in its place, swap it into the index it belongs to.
- Keep swapping at the same i until the right value arrives, then move on.
- Every swap places one item for good, so it is O(n) with no extra memory.
Watch it run
Loading animation…