Cyclic Sort

When values are in the range 1..n, put each number at its own index in O(n) — then missing and duplicate numbers jump out.

Beginner 2 min readLesson 7 of 25

If an array holds numbers from a known range 1..n (or 0..n−1), every value has a "home" index: value v belongs at index v − 1. Cyclic sort swaps each element directly to its home. Each swap places at least one number permanently, so the whole sort is O(n) with O(1) extra space.

30115243243 → index 2
Swap 3 to index 2, then look at what arrived at index 0, and repeat until a[i] == i + 1.
When to use this pattern
  • The input contains numbers in a range like 1..n or 0..n.
  • You need to find missing, duplicate or misplaced numbers.
  • You're asked for O(n) time and O(1) extra space (no hash set allowed).

The template

void cyclicSort(int[] a) {             // values in 1..n
    int i = 0;
    while (i < a.length) {
        int home = a[i] - 1;
        if (a[i] != a[home]) {          // not at home, and the home isn't already holding this value
            int t = a[i]; a[i] = a[home]; a[home] = t;
        } else i++;
    }
}

Comparing a[i] != a[home] (rather than i != home) handles duplicates without infinite loops.

After sorting: scan for anomalies

Any index i where a[i] != i + 1 reveals the story: i + 1 is missing, and a[i] is a duplicate.

Find all missing and duplicate numbers
List<Integer> findDisappeared(int[] a) {
    cyclicSort(a);
    List<Integer> missing = new ArrayList<>();
    for (int i = 0; i < a.length; i++) if (a[i] != i + 1) missing.add(i + 1);
    return missing;
}

List<Integer> findDuplicates(int[] a) {
    cyclicSort(a);
    List<Integer> dups = new ArrayList<>();
    for (int i = 0; i < a.length; i++) if (a[i] != i + 1) dups.add(a[i]);
    return dups;
}

First missing positive (hard, classic)

The array may contain negatives, zeros and huge numbers. Only values in 1..n matter — the answer is always in 1..n+1. Cyclic-sort only the values in range, ignore the rest, then return the first index where a[i] != i + 1.

int firstMissingPositive(int[] a) {
    int n = a.length, i = 0;
    while (i < n) {
        int v = a[i];
        if (v >= 1 && v <= n && a[v - 1] != v) { a[i] = a[v - 1]; a[v - 1] = v; }
        else i++;
    }
    for (i = 0; i < n; i++) if (a[i] != i + 1) return i + 1;
    return n + 1;
}
Practice problems
  • Missing Numbercyclic sort, XOR or sumeasy
  • Find All Numbers Disappeared in an Arrayeasy
  • Set Mismatchone duplicate + one missingeasy
  • Find All Duplicates in an Arraymedium
  • Find the Duplicate Numberor fast/slow if read-onlymedium
  • First Missing Positivehard
  • Kth Missing Positive Numberor binary searcheasy
Key takeaways
  • Values in 1..n each have a home index v − 1.
  • Swap each value home; every swap fixes one value → O(n), O(1) space.
  • Afterwards, mismatched indices expose missing and duplicate values.
  • First missing positive: ignore values outside 1..n.