Cyclic Sort

When an array holds numbers from 1 to n, each value has a home index. Swap every value home in O(n) time and O(1) space, then read the missing and duplicate numbers off the indexes that do not match.

Overview

The idea

Suppose an array of length n holds numbers from the range 1 to n. Then the value v has a natural home: index v - 1. If every number appeared exactly once, the sorted array would be [1, 2, 3, ..., n], with each value sitting at its home. Cyclic sort puts every value that can go home there by swapping, in one pass, without any extra memory. The array acts as its own hash table.

It tests whether you notice the range constraint. A hash set solves missing-number and duplicate questions in O(n) time but O(n) space; sorting takes O(n log n). Cyclic sort gets O(n) time and O(1) extra space, and the questions almost always ask for exactly that.

The whole algorithm is one decision, made again and again at the current index i. Look at v = nums[i], then do one of three things.

  • If v is not in 1..n, it has no home in this array. Move on: i += 1.
  • If nums[v - 1] already holds v, then v is either home or a duplicate whose home holds a copy. Move on: i += 1.
  • Otherwise, swap nums[i] and nums[v - 1], and stay at i.

The index only advances when the value at it is settled: either it is home, it has no home in this array, or its home already holds a copy of it. Notice that after a swap the index does not move. A new value has just arrived at i, and it may need to go home too.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio