Learn / Arrays

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]

ivalueits homeactionarray
032swap[4, 5, 3, 1, 1]
043swap[1, 5, 3, 4, 1]
010home, move on[1, 5, 3, 4, 1]
154swap[1, 1, 3, 4, 5]
110a 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 i forwards after a swap, which leaves the newly arrived value out of place.
  • Comparing home != i instead of nums[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

0 of 4 solved

Check yourself

Values are 1 to n. Which index is the home of value v?

Cyclic sort has a loop that can stay on the same index for several swaps. Why is it still O(n)?

After cyclic sort on values 1 to n with one repeat and one missing, what does index j with nums[j] ≠ j + 1 tell you?

Find the Duplicate Number forbids changing the array. What replaces cyclic sort?