Courses / DSA Patterns for Working Engineers / Chapter 15
Module 5 · Cyclic sort, topological sort, and sort and search · Chapter 15 of 39
Cyclic Sort: Placing Each Value at Its Own Index
Builds on Two Pointers: Pairs, Partitions and In-Place Scans. Next up: Topological Sort: Ordering Tasks by Their Dependencies.
Part 1 · Introduction to cyclic sort
Values that know their cell
Seat numbers, badge numbers and locker numbers are often whole numbers in a small, known range. When the range matches the length of the list, every value already knows which cell it belongs in.
Suppose a list of n values holds the numbers from 1 to n. Sorted, the value 1 sits in cell 0, the value 2 in cell 1, and in general a value v sits in the cell with index v - 1. Call that cell the value's home. Because the home of every value is known without comparing anything, the list can be sorted without a sorting algorithm: send each value to its home.
Cyclic sort does this in place. Look at the cell at index i. If its value v is in the range 1 to n, and its home cell does not already hold v, swap the two cells, so that v lands at home, and look at cell i again, because a new value has arrived there. Otherwise move to cell i + 1. The name comes from the way values travel: a value moves to its home, the value displaced from there moves to its own home, and the chain goes round a cycle until it reaches a cell that is already right.
| Method | Time | Extra space | Needs |
|---|---|---|---|
| Sort the list | O(n log n) | O(1) to O(n) | values that can be compared |
| Count in a Set or an array | O(n) | O(n) | a known range, for the array |
| Cyclic sort | O(n) | O(1) | a known range matching the length, and permission to rearrange |
Why it is linear
Each swap puts a value into its home cell, and a value that is home is never moved again. To see why, suppose a swap moves the value v from cell i to its home h, displacing the value w that sat at h. The swap happens only when w differs from v. If w were at home, its home would be h, so w would equal h + 1, which is v. So w is not home, and the swap does not disturb a value that was in place. Each swap therefore raises the number of cells holding their home value by at least one, and later swaps never undo that.
The number of swaps is then at most n - 1. In a permutation of 1 to n the last swap of every chain puts two values home at once, which keeps the count below n. In a list with repeats or foreign values, not every cell can end up home, so the count stays below n there too. Between swaps the loop only moves i forward, which it does n times. The whole sort is at most about 2n steps.
Counting the swaps
For a permutation the number of swaps is exactly n minus the number of cycles. A cycle is a chain of values that move into one another's homes, such as 4 to the cell of the 1 and 1 to the cell of the 4, and a cycle of length L takes L - 1 swaps. A list that is already sorted has n cycles of length one and needs no swaps, while a list rotated by one place is a single cycle and needs n - 1. The scene sorts six values.
Watch for each swap sending a value to its home cell, index value minus 1, for good
Read it as steps
every swap puts one value in its home cell for good, and four swaps sort six values
The six values formed two cycles, a short one of the 4 and the 1 and a long one through 6, 5, 3 and 2, and took 1 + 3 = 4 swaps, which is 6 - 2.
The code
The function below is the version used for the rest of the chapter. It ignores values outside 1 to n, and also ignores a value whose home already holds the same value, which is a repeat. Both cases leave the value where it is.
Swaps are counted in a small Stats object, which the later lessons import together with cyclicSort from this file.
export interface Stats { swaps: number }
// Puts every value v with 1 <= v <= n at index v - 1, where n is the // length. Values outside 1..n, and extra copies of a value, stay in // whatever cells are left. Works in place, with O(1) extra space. export function cyclicSort( a: number[], stats: Stats = { swaps: 0 }, ): void { let i = 0 while (i < a.length) { const home = a[i] - 1 if (home >= 0 && home < a.length && a[home] !== a[i]) { ;[a[i], a[home]] = [a[home], a[i]] stats.swaps++ } else { i++ } } }
The comparison a[home] !== a[i] replaces the simpler home !== i so that a repeated value cannot make two cells swap forever: if the home cell already holds the same number, swapping would change nothing, and the loop would never move on.
The run counts swaps for a random permutation of 1,00,000 values, a rotation by one place, and a sorted list, and checks the n minus cycles rule on 1,000 small permutations. It uses a seeded shuffle, which is the Fisher-Yates method, and a function that counts cycles.
// Fisher-Yates: a uniformly random order, from a seeded generator. export function shuffle<T>(a: T[], rand: () => number): T[] { for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(rand() * (i + 1)) ;[a[i], a[j]] = [a[j], a[i]] } return a }
const rand = mulberry32(21) function shuffled(n: number): number[] { return shuffle(Array.from({ length: n }, (_, i) => i + 1), rand) } // Number of cycles in the permutation i -> a[i] - 1. function cycles(a: number[]): number { const seen = new Array<boolean>(a.length).fill(false) let count = 0 for (let i = 0; i < a.length; i++) { if (seen[i]) continue count++ for (let j = i; !seen[j]; j = a[j] - 1) seen[j] = true } return count }
function swapsFor(a: number[]): number { const stats = { swaps: 0 } cyclicSort(a, stats) return stats.swaps } const n = 100_000 const big = shuffled(n) const c = cycles(big) console.log('random permutation, n =', n) const swaps = swapsFor(big) console.log(' swaps', swaps, ' cycles', c, ' n - cycles', n - c) const rotated = Array.from({ length: n }, (_, i) => ((i + 1) % n) + 1) const worst = swapsFor(rotated) console.log('rotated by one: swaps', worst, ' (n - 1 =', n - 1 + ')') const sorted = Array.from({ length: n }, (_, i) => i + 1) console.log('already sorted: swaps', swapsFor(sorted)) let allEqual = true for (let t = 0; t < 1000; t++) { const p = shuffled(1 + Math.floor(rand() * 40)) const expect = p.length - cycles(p) allEqual = allEqual && swapsFor(p) === expect } console.log('1000 small permutations, swaps = n - cycles:', allEqual)
Checking it, and where it stops
The random permutation needed 99,989 swaps and had 11 cycles, and 1,00,000 - 11 = 99,989. The rotation by one place needed the worst case, 99,999, and the sorted list none. The 1,000 small permutations all matched the rule.
Cyclic sort is not a general sort. It can place a value only when the value is a valid cell number, so it cannot sort amounts or timestamps. The run below passes a list of amounts and a list of ids.
const amounts = [30, 10, 20] cyclicSort(amounts) console.log('values outside 1..3 stay put:', amounts.join(' ')) const ids = [3, 1, 2] cyclicSort(ids) console.log('values inside 1..3 are sorted:', ids.join(' '))
values outside 1..3 stay put: 30 10 20 values inside 1..3 are sorted: 1 2 3
Output of one run
The amounts 30, 10 and 20 are all outside the range 1 to 3, so none moves, and the list comes back unchanged. The ids are inside the range and come back sorted.
test('a permutation gets sorted, a sorted one is untouched', () => { const a = [3, 1, 4, 2] cyclicSort(a) assert.deepEqual(a, [1, 2, 3, 4]) const stats = { swaps: 0 } cyclicSort([1, 2, 3], stats) assert.equal(stats.swaps, 0) }) test('out-of-range values and repeats stay out of the way', () => { const a = [7, 2, 2, -1, 1] cyclicSort(a) assert.equal(a[0], 1) assert.equal(a[1], 2) assert.deepEqual(a.slice(2).toSorted((p, q) => p - q), [-1, 2, 7]) }) test('never more than n - 1 swaps on 2000 random permutations', () => { const rand = mulberry32(8) for (let t = 0; t < 2000; t++) { const n = 1 + Math.floor(rand() * 30) const a = shuffle(Array.from({ length: n }, (_, i) => i + 1), rand) const stats = { swaps: 0 } cyclicSort(a, stats) assert.ok(stats.swaps <= n - 1) assert.deepEqual(a, Array.from({ length: n }, (_, i) => i + 1)) } })
✔ a permutation gets sorted, a sorted one is untouched (1.0964ms) ✔ out-of-range values and repeats stay out of the way (0.1367ms) ✔ never more than n - 1 swaps on 2000 random permutations (11.1693ms) ℹ tests 3 ℹ pass 3 ℹ fail 0
Output of one run, excerpt; the millisecond figures vary
In a list of 10 values from 1 to 10, which cell is the home of the value 7?
- Index 6. A value v belongs at index v - 1.
How many swaps does cyclic sort need for the list 2, 3, 4, 5, 1, and why?
Part 2 · The missing seat number
The problem
A hall has seats numbered 0 to n. After a show, the scanner records the seat of every ticket it scanned, in the order they came, but one seat stayed empty. The record is a list of n different numbers between 0 and n. Which seat is missing?
There are three ways to find it. The first is arithmetic: the numbers 0 to n add up to n(n + 1) / 2, so the missing seat is that total minus the sum of the list. It is O(n) time and O(1) space. The second is a Set: put the numbers in, then look for the first seat from 0 that is absent, at the cost of O(n) space. The third is cyclic sort, which also runs in O(n) time and O(1) space.
The sum is the best answer to this exact problem. Cyclic sort is worth learning because the sum cannot do the harder versions, where several numbers are missing or numbers repeat. This lesson solves the single missing seat, and then the version with repeats, to show the step that carries over.
Sorting the values, then scanning
Seat numbers start at 0 here, so the home of a value v is index v, not v - 1. The list has n cells and holds values up to n, so the value n has no cell. It is left where it is. After sorting, every other value is in its cell, so the first cell i whose value is not i is the position of the missing seat. If every cell is right, the missing seat is n.
// Seats 0..n with one missing: a holds n different values from 0 to n. // Value v belongs at index v, so value n has no cell and stays put. export function missingSeat(a: number[]): number { const b = a.slice() let i = 0 while (i < b.length) { const v = b[i] if (v < b.length && b[v] !== v) { ;[b[i], b[v]] = [b[v], b[i]] } else { i++ } } for (let j = 0; j < b.length; j++) if (b[j] !== j) return j return b.length }
The second version has numbers from 1 to n and repeats allowed, with the goal of listing every number from 1 to n that is absent. Cyclic sort leaves every present value at home. A cell holding something else must have a home value that is absent: if the number i + 1 were present anywhere in the list, the sort would have put it in cell i. So each cell i that does not hold i + 1 reveals the missing number i + 1.
// Values from 1 to n, repeats allowed: every number from 1 to n // that does not appear. export function allMissing(a: number[]): number[] { const b = a.slice() cyclicSort(b) const out: number[] = [] for (let j = 0; j < b.length; j++) if (b[j] !== j + 1) out.push(j + 1) return out }
The references are the sum and the Set, used to check both functions.
// References: a sum, and a set. export function missingSeatBySum(a: number[]): number { const n = a.length return (n * (n + 1)) / 2 - a.reduce((p, q) => p + q, 0) } export function allMissingBySet(a: number[]): number[] { const seen = new Set(a) const out: number[] = [] for (let v = 1; v <= a.length; v++) if (!seen.has(v)) out.push(v) return out }
Running it
const seats = [5, 0, 3, 1, 4] console.log('seats', seats.join(' '), '-> missing', missingSeat(seats)) console.log('all present but the last:', missingSeat([0, 1, 2])) console.log('only seat 0 missing:', missingSeat([1, 2, 3])) console.log('one seat only:', missingSeat([1]), missingSeat([0])) const tags = [6, 2, 2, 5, 1, 6, 3, 3] const gaps = allMissing(tags).join(' ') console.log('tags', tags.join(' '), '-> missing', gaps) console.log('input still', tags.join(' '))
seats 5 0 3 1 4 -> missing 2 all present but the last: 3 only seat 0 missing: 0 one seat only: 0 1 tags 6 2 2 5 1 6 3 3 -> missing 4 7 8 input still 6 2 2 5 1 6 3 3
Output of one run
In the list 5, 0, 3, 1, 4 the seat 2 is missing. When the missing seat is the last one, 3 in the list 0, 1, 2, the answer is n. When seat 0 is missing, the sort leaves cell 0 holding a larger value and reports 0. A single seat is handled both ways: the list [1] misses 0 and the list [0] misses 1.
For the list of tags 6, 2, 2, 5, 1, 6, 3, 3, the numbers 4, 7 and 8 never appear, and the repeats 2, 6 and 3 take up the cells that belong to them. The functions copy the input, so the last line of the demo shows the original list is unchanged.
Checking it
The tests cover the edges, and then 2,000 random cases: a seat removed from the full set and the list shuffled, compared with the sum, and a random list with repeats, compared with the Set.
test('missing seat: edges', () => { assert.equal(missingSeat([0]), 1) assert.equal(missingSeat([1]), 0) assert.equal(missingSeat([]), 0) }) test('same answers as the sum and the set, 2000 random inputs', () => { const rand = mulberry32(30) for (let t = 0; t < 2000; t++) { const n = 1 + Math.floor(rand() * 12) const seats = Array.from({ length: n + 1 }, (_, i) => i) const gone = Math.floor(rand() * (n + 1)) const a = shuffle(seats.filter((v) => v !== gone), rand) assert.equal(missingSeat(a), gone) assert.equal(missingSeatBySum(a), gone) const b = Array.from({ length: n }, () => { return 1 + Math.floor(rand() * n) }) assert.deepEqual(allMissing(b), allMissingBySet(b)) } })
✔ missing seat: edges (0.6392ms) ✔ same answers as the sum and the set, 2000 random inputs (13.4806ms) ℹ tests 2 ℹ pass 2 ℹ fail 0
Output of one run, excerpt; the millisecond figures vary
Related on LeetCode: Missing Number, Find All Numbers Disappeared in an Array.
Seats 0 to 4 and the scanned list is 4, 2, 0, 1. Which seat is missing, and what does cyclic sort leave in cell 3?
- Seat 3. After sorting the list is 0, 1, 2, 4, with the 4 left in cell 3 because it has no cell of its own, so the first cell that is wrong is cell 3.
Why is the sum method not enough for finding all numbers missing from a list with repeats?
- The sum only reveals the combined effect of the missing and repeated numbers, not which numbers they are. Cyclic sort leaves each wrong cell at a position that names a missing number.
Why do the functions work on a copy?
- Cyclic sort rearranges the list. A copy keeps the caller's original order. If the caller does not need the original order, the copy can be dropped.
Part 3 · A badge printed twice
The problem
A conference prints badges numbered 1 to n, one for each of n attendees. A printer fault repeats one number and skips another, so the printed list has n numbers where one appears twice and one never appears. Which number was printed twice, and which was skipped?
With a Map of counts the answer takes one pass and O(n) space: find the count of 2 and the number with no entry. Cyclic sort does it with no extra memory. The reason it works is a short counting argument, given below.
After the sort, every present number from 1 to n is at its home cell. All numbers are present except the skipped one, and the repeated number is present twice. The repeated number fills its home cell with one copy, and the other copy has nowhere to go. The skipped number's home cell cannot hold its own value, so it holds the spare copy. So exactly one cell is wrong: the home cell of the skipped number, holding the repeated number.
Reading the answer from the wrong cell
This gives the whole solution. Sort a copy, then find the one cell i whose value is not i + 1. The value in it is the number printed twice and i + 1 is the number skipped. For a list that has no mismatch at all, there is no wrong cell, and the function reports an error.
// Badge numbers 1..n were printed, but one number was printed twice and // another not at all. Returns both. export function badgeMix( a: number[], ): { twice: number; missing: number } { const b = a.slice() cyclicSort(b) for (let i = 0; i < b.length; i++) { if (b[i] !== i + 1) return { twice: b[i], missing: i + 1 } } throw new Error('no mismatch: the input was already 1..n') }
A second problem has the same shape with a looser promise: every number from 1 to n appears once or twice, and some do not appear at all. Which numbers appear twice? Every present number has its home cell filled by one copy. A second copy of a number has no home, and it can only sit in a cell that belongs to an absent number, so every wrong cell holds a number that appears twice, and each such number is in exactly one wrong cell. Collecting the values of the wrong cells gives the answer.
// Every number appears once or twice. Returns those that appear twice. export function printedTwice(a: number[]): number[] { const b = a.slice() cyclicSort(b) const out: number[] = [] for (let i = 0; i < b.length; i++) if (b[i] !== i + 1) out.push(b[i]) return out }
The reference counts numbers with a Map.
// References: count with a Map. export function badgeMixByCount(a: number[]) { const counts = new Map<number, number>() for (const v of a) counts.set(v, (counts.get(v) ?? 0) + 1) let twice = 0 let missing = 0 for (let v = 1; v <= a.length; v++) { if (counts.get(v) === 2) twice = v if (!counts.has(v)) missing = v } return { twice, missing } }
Running it
const badges = [3, 5, 1, 5, 2, 6] console.log(badges.join(' '), '->', badgeMix(badges)) const crates = [5, 3, 1, 3, 6, 1, 4] console.log(crates.join(' '), '-> twice:', printedTwice(crates)) console.log('no repeats:', printedTwice([2, 1, 3]))
3 5 1 5 2 6 -> { twice: 5, missing: 4 } 5 3 1 3 6 1 4 -> twice: [ 1, 3 ] no repeats: []
Output of one run
The badges 3, 5, 1, 5, 2, 6 print the 5 twice and skip the 4. For the crates 5, 3, 1, 3, 6, 1, 4, the numbers 1 and 3 each appear twice, and 2 and 7 do not appear. A list where every number appears exactly once has no repeats, so the function returns an empty list.
The values come out in the order of the wrong cells, which is by the number the cell belongs to, not by the repeated number. A caller who needs them in increasing order sorts the short result.
One repeated number among n + 1
A third problem changes the promise again: a list of n + 1 numbers, each from 1 to n. Some number must repeat, by the pigeonhole principle, and it may repeat many times. There is no missing number to find, only a repeat. Cyclic sort still helps: swap values home as before, and stop the moment a value's home cell already holds that same value while the value sits in a different cell. That value has two copies.
The list has n + 1 cells and no value n + 1, so the last cell never holds its own number. Each swap still puts a value home for good, so the loop ends, and it can only end by finding a repeat, because a list with no repeat would need n + 1 different values from only n possible numbers.
// n + 1 numbers, each from 1 to n, so at least one number repeats and // it may repeat many times. Returns one repeated number. export function findDuplicate(a: number[]): number { const b = a.slice() let i = 0 while (i < b.length) { const home = b[i] - 1 if (b[i] === i + 1) i++ else if (b[home] === b[i]) return b[i] // its home is already taken else [b[i], b[home]] = [b[home], b[i]] } throw new Error('no duplicate: the input broke the promise') }
console.log(findDuplicate([4, 2, 5, 1, 3, 5])) console.log(findDuplicate([2, 6, 2, 3, 2, 5, 2])) console.log(findDuplicate([1, 3, 3, 3]))
5 2 3
Output of one run
The second list repeats 2 four times and the third list repeats 3 three times, and one repeated value is returned in each case. When the list has several repeated values, which one is returned depends on the order of the swaps. The function works on a copy, so it uses O(n) extra space; if the caller allows the list to be reordered, drop the copy and the space is O(1). The reference remembers what it has seen in a Set.
// Reference: remember what has been seen. export function findDuplicateBySet(a: number[]): number { const seen = new Set<number>() for (const v of a) { if (seen.has(v)) return v seen.add(v) } throw new Error('no duplicate') }
test('a repeated number is found, and the input is kept', () => { const a = [6, 1, 4, 2, 6, 3, 5] assert.equal(findDuplicate(a), 6) assert.deepEqual(a, [6, 1, 4, 2, 6, 3, 5]) }) test('3000 random lists, with many repeats too', () => { const rand = mulberry32(52) for (let t = 0; t < 3000; t++) { const n = 1 + Math.floor(rand() * 10) const spread = 1 + Math.floor(rand() * n) // few distinct values const a = Array.from({ length: n + 1 }, () => { return 1 + Math.floor(rand() * spread) }) const v = findDuplicate(a) assert.equal(a.filter((x) => x === v).length > 1, true) } })
Checking it
The tests cover the two-badge case, 2,000 random mix-ups compared with counting, and a list with a mixture of single and double numbers. Each mix-up takes the numbers 1 to n, overwrites one with a copy of another, and shuffles.
test('smallest case: two badges', () => { assert.deepEqual(badgeMix([3, 3, 1]), { twice: 3, missing: 2 }) assert.deepEqual(badgeMix([2, 2]), { twice: 2, missing: 1 }) }) test('random mix-ups match counting, 2000 cases', () => { const rand = mulberry32(44) for (let t = 0; t < 2000; t++) { const n = 2 + Math.floor(rand() * 12) const a = Array.from({ length: n }, (_, i) => i + 1) const gone = Math.floor(rand() * n) let copy = Math.floor(rand() * n) if (copy === gone) copy = (copy + 1) % n a[gone] = a[copy] shuffle(a, rand) assert.deepEqual(badgeMix(a), badgeMixByCount(a)) } }) test('numbers printed twice, in a mix of single and double', () => { const a = [2, 1, 4, 4, 3, 2] assert.deepEqual(printedTwice(a).toSorted((p, q) => p - q), [2, 4]) })
✔ smallest case: two badges (1.015ms) ✔ random mix-ups match counting, 2000 cases (10.6539ms) ✔ numbers printed twice, in a mix of single and double (0.3342ms) ℹ tests 3 ℹ pass 3 ℹ fail 0
Output of one run, excerpt; the millisecond figures vary
Related on LeetCode: Set Mismatch, Find All Duplicates in an Array.
The list is 2, 4, 4, 1. After cyclic sort, which cell is wrong and what does that tell you?
- The sorted list is 1, 2, 4, 4. Cell 2 holds 4 where 3 should be, so 4 was printed twice and 3 was skipped.
Why is exactly one cell wrong in the badge problem?
- Every number except the skipped one fills its home cell. The second copy of the repeated number must go somewhere, and the only cell not taken by its own number is the home of the skipped number.
For the crates problem, why does every wrong cell hold a number that appears twice?
- Each present number takes its home cell with one copy. A cell that does not hold its own number holds a leftover second copy, and a number that has a leftover appears twice.
Part 4 · The smallest free locker
The problem
A gym hands out lockers numbered 1, 2, 3 and so on. Its records are a list of locker numbers that are in use, but the list is messy: it may hold zeros, negative numbers from data-entry mistakes, numbers far beyond any real locker, and repeats. The question is the smallest locker number, from 1 upwards, that is free.
A Set answers it in O(n) space: put every number in, then count up from 1 until one is missing. Cyclic sort answers it in O(1) extra space, once one observation is made.
The observation is that the answer lies between 1 and n + 1, where n is the length of the list. If the numbers 1 to n are all present, the list is full and the answer is n + 1. If any of them is absent, the smallest absent one is at most n. In either case the answer cannot be above n + 1, since n values cannot cover n + 1 different numbers (the pigeonhole principle). So values below 1 and above n can never matter and can be ignored, which is exactly what the sort of the previous lessons does with them.
Sort, then find the first wrong cell
Run cyclic sort on a copy. Values from 1 to n go home, and everything else stays in whatever cells are left over. Then scan from the first cell. The first cell i whose value is not i + 1 shows that the number i + 1 is not in the list, so the answer is i + 1. If every cell is right, the answer is n + 1.
// The smallest locker number from 1 upwards that nobody holds. The // list may hold zeros, negatives, huge numbers and repeats; it is // not changed. export function smallestFree(a: number[]): number { const b = a.slice() cyclicSort(b) // values outside 1..n are left alone for (let i = 0; i < b.length; i++) { if (b[i] !== i + 1) return i + 1 } return b.length + 1 }
The scene follows eight values, with a zero, a negative number, a number far out of range and a repeat. It shows the three kinds of value that stay still.
Watch for values outside 1 to 8 staying where they are, and for the first wrong cell
Read it as steps
out-of-range values stay put, and the first cell that is wrong gives the answer
The first wrong cell was cell 2, which holds the leftover -3, so locker 3 is free. Cell 0 and cell 1 ended up holding the 1 and the 2, so those lockers are taken. The 3 never reached cell 2 because it is not in the list, and the cell holds a value with no home instead.
Running it
const lockers = [8, -3, 2, 0, 1, 900, 2, 4] console.log(lockers.join(' '), '->', smallestFree(lockers)) console.log('1 is taken, nothing else:', smallestFree([1])) console.log('only huge numbers:', smallestFree([40, 50, 60])) console.log('a full block 1..4:', smallestFree([3, 1, 4, 2])) console.log('empty list:', smallestFree([]))
8 -3 2 0 1 900 2 4 -> 3 1 is taken, nothing else: 2 only huge numbers: 1 a full block 1..4: 5 empty list: 1
Output of one run
The first line is the scene's list, answered 3. A list that holds only 1 has the answer 2. A list of numbers all above the length gives 1. A full block 1 to 4 gives 5, which is n + 1. An empty list gives 1.
The Set reference is short and is used to check the sort on thousands of random inputs.
// Reference: put everything in a Set and count up from 1. export function smallestFreeBySet(a: number[]): number { const seen = new Set(a) let v = 1 while (seen.has(v)) v++ return v }
Why repeats need the comparison with the home cell
The chapter's cyclicSort tests a[home] !== a[i]. The simpler test, home !== i, looks equivalent and is what many first versions use. It is correct for a list of different values, and it fails on any list with a repeat: when two cells hold the same value, the first cell's home is the second cell, which already holds that value, and swapping them changes nothing. The loop then swaps the same two cells for ever, because i never moves on.
// The simpler test, home !== i, with a guard that stops runaway loops. function naiveSort(a: number[], maxSteps: number): number { let i = 0 let steps = 0 while (i < a.length && steps < maxSteps) { steps++ const home = a[i] - 1 if (home >= 0 && home < a.length && home !== i) { ;[a[i], a[home]] = [a[home], a[i]] } else { i++ } } return steps }
const clean = [3, 1, 2] const ok = naiveSort(clean, 1000) console.log('permutation:', ok, 'steps ->', clean.join(' ')) const dirty = [8, 2, 2, 5] const steps = naiveSort(dirty, 1000) console.log('with a repeat:', steps, 'steps, stopped by the guard') console.log('list now', dirty.join(' '))
permutation: 5 steps -> 1 2 3 with a repeat: 1000 steps, stopped by the guard list now 8 2 2 5
Output of one run
On the permutation 3, 1, 2 the simple test finishes in 5 steps and sorts it. On 8, 2, 2, 5 it never finishes: the 8 is skipped, the first 2 is home, and the second 2 swaps with the first one for ever, until the guard stops the loop after 1,000 steps. A list read from a messy file can contain repeats at any time, so the version with the value comparison is the safe one. The same guard is a useful habit when you first write a loop whose progress depends on a swap changing something.
Checking it
The tests cover an empty list, negatives only, zeros only, a check that the input is not changed, and 3,000 random lists with numbers from -4 to 15, compared with the Set.
test('empty, negatives only, zeros only', () => { assert.equal(smallestFree([]), 1) assert.equal(smallestFree([-5, -1]), 1) assert.equal(smallestFree([0, 0, 0]), 1) }) test('the input is left unchanged', () => { const a = [3, 1, 7, 2] smallestFree(a) assert.deepEqual(a, [3, 1, 7, 2]) }) test('same answer as a Set, 3000 random lists', () => { const rand = mulberry32(77) for (let t = 0; t < 3000; t++) { const n = Math.floor(rand() * 12) const a = Array.from({ length: n }, () => { return Math.floor(rand() * 20) - 4 }) assert.equal(smallestFree(a), smallestFreeBySet(a)) } })
✔ empty, negatives only, zeros only (1.106ms) ✔ the input is left unchanged (0.7012ms) ✔ same answer as a Set, 3000 random lists (7.7872ms) ℹ tests 3 ℹ pass 3 ℹ fail 0
Output of one run, excerpt; the millisecond figures vary
Related on LeetCode: First Missing Positive.
A list has length 4 and holds 1, 2, 3, 4. What is the smallest free locker?
- 5, which is n + 1. Every number from 1 to n is taken.
Why can the values 0, -7 and 500 in a list of length 6 be ignored?
- The answer is at most n + 1 = 7, so values below 1 or above 6 cannot be the smallest missing number, and they cannot occupy a home cell either.
Why does the sort not change the answer when a number appears twice?
- One copy takes the home cell. The other copy stays out of place in some other cell, where it cannot make a wrong cell look right: the first wrong cell is still the first number that is absent.
Part 5 · The first k free token numbers
The problem
A queue system hands out token numbers 1, 2, 3 and so on. The counters keep a list of tokens that are already taken, in no order and with repeats. A new batch of k tokens must be issued: the k smallest numbers, from 1 upwards, that are not taken. If k is larger than the list, the numbers beyond the length of the list also count, and some of those may be taken too.
This extends the previous lesson. The smallest free number is the first of the k, and the others follow. They come from two places: the numbers from 1 to n that are free, and, if more are needed, the numbers above n.
Free numbers from 1 to n are found as before. After the sort, a cell i that does not hold i + 1 shows that i + 1 is absent, so i + 1 is free, and the cells give these numbers in increasing order. The cell also holds a value that did not find its home, and that value may be above n. Those values are the numbers above n that are taken. Keep them in a Set.
Continuing past n
If the cells give fewer than k free numbers, continue counting from n + 1 and report each number that is not in the Set of taken numbers above n. This is safe because the Set holds every taken number above n: a taken number above n has no home cell, so it cannot be home, so it was left in a cell that is wrong, and the scan recorded it.
// The first k token numbers from 1 upwards that nobody holds. The list // may hold any integers; it is not changed. export function freeTokens(a: number[], k: number): number[] { const b = a.slice() cyclicSort(b) const free: number[] = [] const seenOutOfPlace = new Set<number>() for (let i = 0; i < b.length; i++) { if (b[i] !== i + 1) { if (free.length < k) free.push(i + 1) seenOutOfPlace.add(b[i]) // may be a number above n that is taken } } for (let v = b.length + 1; free.length < k; v++) { if (!seenOutOfPlace.has(v)) free.push(v) } return free }
The cost is O(n + k) time. The extra space is no longer O(1): the Set can hold up to n values. If only the free numbers up to n are needed, no Set is required and the extra space drops back to O(1). The Set exists only to skip taken numbers while counting past n.
A reference that does not use cyclic sort puts every number in a Set and counts up from 1.
// Reference: a Set, counting up from 1 until k numbers are found. export function freeTokensBySet(a: number[], k: number): number[] { const seen = new Set(a) const free: number[] = [] for (let v = 1; free.length < k; v++) if (!seen.has(v)) free.push(v) return free }
Running it
const tokens = [3, 9, 1, 12, 3, 7] console.log(tokens.join(' ')) for (const k of [1, 3, 5, 8]) { console.log('first', k, 'free:', freeTokens(tokens, k).join(' ')) }
3 9 1 12 3 7 first 1 free: 2 first 3 free: 2 4 5 first 5 free: 2 4 5 6 8 first 8 free: 2 4 5 6 8 10 11 13
Output of one run
The list 3, 9, 1, 12, 3, 7 has length 6. The free numbers up to 6 are 2, 4, 5 and 6, so the first three tokens come from the cells. For five tokens the fifth is 8, past the length, and 7 is skipped because it is taken. With eight tokens the list continues 10 and 11 and then 13, skipping the taken 12.
To see where those answers come from, look at the list after the sort.
const tokens = [3, 9, 1, 12, 3, 7] cyclicSort(tokens) console.log('after the sort:', tokens.join(' ')) const wrong: string[] = [] tokens.forEach((v, i) => { if (v !== i + 1) wrong.push(`cell ${i} holds ${v}`) }) console.log(wrong.join('; '))
after the sort: 1 9 3 12 3 7 cell 1 holds 9; cell 3 holds 12; cell 4 holds 3; cell 5 holds 7
Output of one run
Cells 1, 3, 4 and 5 are wrong, so the numbers 2, 4, 5 and 6 are free. The wrong cells hold 9, 12, 3 and 7. The 3 is a repeat, since cell 2 already holds a 3, and the other three are taken numbers above n: 7, 9 and 12. They are what the counting past n has to skip.
Checking it
The tests cover k of 0 and an empty list, two lists where k is larger than the length and the count has to skip numbers that are taken, and 3,000 random lists compared with the Set reference.
test('k = 0, and an empty list', () => { assert.deepEqual(freeTokens([5, 6], 0), []) assert.deepEqual(freeTokens([], 3), [1, 2, 3]) }) test('k beyond n continues past n and skips taken numbers', () => { assert.deepEqual(freeTokens([1, 2, 5], 3), [3, 4, 6]) assert.deepEqual(freeTokens([2, 7, 8], 4), [1, 3, 4, 5]) }) test('same answer as a Set, 3000 random lists', () => { const rand = mulberry32(61) for (let t = 0; t < 3000; t++) { const n = Math.floor(rand() * 10) const a = Array.from({ length: n }, () => { return Math.floor(rand() * 25) - 3 }) const k = Math.floor(rand() * 12) assert.deepEqual(freeTokens(a, k), freeTokensBySet(a, k)) } })
✔ k = 0, and an empty list (1.7027ms) ✔ k beyond n continues past n and skips taken numbers (0.2236ms) ✔ same answer as a Set, 3000 random lists (16.313ms) ℹ tests 3 ℹ pass 3 ℹ fail 0
Output of one run, excerpt; the millisecond figures vary
Related on LeetCode: Kth Missing Positive Number. The linked problem gives a sorted list; this lesson's version takes an unsorted list.
The taken tokens are 1, 2, 5 and k = 3. Which tokens are issued?
- 3, 4 and 6. The cells give 3. Counting past n = 3 gives 4, then skips 5, which is taken, and gives 6.
Why does the code keep a Set of values from the wrong cells?
- Taken numbers above n have no home cell, so they remain in wrong cells. The Set lets the count past n skip them.
When is no Set needed?
- When k is no larger than the number of free numbers from 1 to n, because then the cells give every token and no counting past n happens.
All chapters · Previous: Dynamic Programming: States, Transitions and Tables