Some array problems come with a gift hidden in the constraints: the values in the array are drawn from a small, known range — usually 1 to n, or 0 to n-1 — even though the array itself isn’t sorted.
Some array problems come with a gift hidden in the constraints: the values in the array are drawn from a small, known range — usually 1 to n, or 0 to n-1 — even though the array itself isn’t sorted. That gift is easy to miss if you’re used to reaching for a hash set the moment you see “find the missing” or “find the duplicate.” A hash set works, and it’s a perfectly reasonable first answer. But when the interviewer follows up with “can you do it without the extra memory?”, cyclic sort is almost always the tool they’re fishing for.
The core idea is simple: if you know a value v belongs at index v - 1 (or v for a zero-indexed variant), you can walk the array once and repeatedly swap each element toward its “home” position. Every swap places at least one value where it belongs, so the whole process finishes in linear time even though it looks like it might be doing more work than a single pass. Once the array is arranged this way — or as close to arranged as the data allows — missing values, duplicates, and other range violations show up as positions where array[i] != i + 1. You don’t need to build an auxiliary structure to notice them; the array becomes its own lookup table.
The signal to watch for is specific. You’re looking at cyclic sort when the values are integers bounded by the array’s own length (explicitly “1 to n” or “0 to n-1,” or a range you can derive from n), when the problem mentions a single missing, duplicated, or out-of-place value, and when there’s an explicit or implied bonus for solving it in O(1) extra space. A closely related trick — index marking, where you flip the sign of the value at an index to record “I’ve seen this number” instead of physically swapping — solves a similar family of problems and is worth knowing as a lower-overhead cousin of full cyclic sort. Both techniques fall apart the moment the value range isn’t tied to the array’s length; if the values are arbitrary integers or floats, reach for a hash set instead, because there’s no “home index” to sort them toward.
Continue with the book
Explore the full treatment, worked examples, and exercises in Algorithmic Edge.
Companion article for Algorithmic Edge, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.
