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.
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.
- 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++;
}
}def cyclic_sort(a): # values in 1..n
i = 0
while i < len(a):
home = a[i] - 1
if a[i] != a[home]:
a[i], a[home] = a[home], a[i]
else:
i += 1function cyclicSort(a: number[]) { // values in 1..n
let i = 0;
while (i < a.length) {
const home = a[i] - 1;
if (a[i] !== a[home]) [a[i], a[home]] = [a[home], a[i]];
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.
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;
}def find_disappeared(a):
cyclic_sort(a)
return [i + 1 for i, x in enumerate(a) if x != i + 1]
def find_duplicates(a):
cyclic_sort(a)
return [x for i, x in enumerate(a) if x != i + 1]function findDisappeared(a: number[]): number[] {
cyclicSort(a);
return a.flatMap((x, i) => (x !== i + 1 ? [i + 1] : []));
}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;
}def first_missing_positive(a):
n, i = len(a), 0
while i < n:
v = a[i]
if 1 <= v <= n and a[v - 1] != v:
a[i], a[v - 1] = a[v - 1], v
else:
i += 1
for i in range(n):
if a[i] != i + 1:
return i + 1
return n + 1function firstMissingPositive(a: number[]): number {
const n = a.length;
let i = 0;
while (i < n) {
const 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;
}- 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
- 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.