Leaderboards, trending lists and nearest-shop searches all ask for the best few items out of a very large pile. Sorting the whole pile is more work than the question needs.
Many questions ask for the best few of many: the five biggest orders, the ten nearest shops, the three most searched words. These are top k questions: given n items and a number k, return the k items that rank highest, or the one that ranks kth. Nothing in the question needs the other n - k items sorted.
Sorting everything is correct but does more than the question asks. A sort costs about n log n comparisons however small k is: on 10 lakh values, close to 2 crore comparisons to find five numbers. Three tools get the same answer with less work.
Tool
Idea
Time
Extra space
Works when
Size-k heap
Keep the k best so far; compare each new value with the weakest kept
O(n log k)
O(k)
Any orderable values, even a stream
Bucket counts
Count each value, then read the counts from the top
O(n + m) for m possible values
O(m)
Whole numbers in a small known range
Quickselect
Partition around a pivot and keep the side holding the target
O(n) expected, O(n^2) worst
O(1) beyond the array
The array is in memory and may be reordered
Size-k heap
IdeaKeep the k best so far; compare each new value with the weakest kept
TimeO(n log k)
Extra spaceO(k)
Works whenAny orderable values, even a stream
Bucket counts
IdeaCount each value, then read the counts from the top
TimeO(n + m) for m possible values
Extra spaceO(m)
Works whenWhole numbers in a small known range
Quickselect
IdeaPartition around a pivot and keep the side holding the target
TimeO(n) expected, O(n^2) worst
Extra spaceO(1) beyond the array
Works whenThe array is in memory and may be reordered
Everything here is written for the k largest. For the k smallest, flip every comparison: a max-heap replaces the min-heap, and quickselect aims at index k - 1 instead of n - k.
The size-k heap
A min-heap keeps its smallest item at the root and returns it in constant time with peek. Store the k largest values in a min-heap and the root is the weakest of the k, which is exactly the value a newcomer has to beat. The rule for each new value is short.
While the heap holds fewer than k values, push the new value.
Otherwise compare the new value with the root. If it is not larger, throw it away.
If it is larger, pop the root and push the new value.
Why this is correct: after every step the heap holds the k largest values seen so far, or all of them while fewer than k have arrived. A thrown-away value was not larger than the root, and the heap already holds k values that are at least as large as the root, so the thrown value cannot be among the k largest. A value that is larger than the root joins the k values already kept, giving k + 1 candidates, and the root is the smallest of them, so removing it leaves the k largest. Every step does nothing or one pop and one push, each O(log k), so n values cost O(n log k) at worst.
Animated sceneA size-3 min-heap over a stream0:21
Watch for small values being rejected and large ones pushing the smallest out
Read it as steps
small values are rejected at the root, large ones push the smallest out
The scene ran the rule with k = 3 on seven values. The values 3 and 5 were rejected with one comparison each, and 8 and 10 each replaced the root. The heap never held more than three values.
Buckets, quickselect and the heap class
The lessons use the heap class from the two heaps chapter. Save it as heap.ts. Its constructor takes a function less that says which of two items belongs nearer the root: (a, b) => a < b gives a min-heap of numbers, and a function that returns true when the first argument is larger gives a max-heap.
ts
exportclass Heap<T> {
items: T[] = []
less: (a: T, b: T) => boolean
constructor(less: (a: T, b: T) => boolean) {
this.less = less
}
get size(): number {
returnthis.items.length
}
peek(): T | undefined {
returnthis.items[0]
}
push(x: T): void {
this.items.push(x)
this.siftUp(this.items.length - 1)
}
siftUp(i: number): void {
const a = this.items
while (i > 0) {
const p = (i - 1) >> 1if (!this.less(a[i], a[p])) return
;[a[i], a[p]] = [a[p], a[i]]
i = p
}
}
ts
pop(): T | undefined {
const a = this.items
if (a.length === 0) returnundefinedconst top = a[0]
const last = a.pop() as T
if (a.length > 0) {
a[0] = last
this.siftDown(0)
}
return top
}
siftDown(i: number): void {
const a = this.items
for (;;) {
let m = i
const l = 2 * i + 1const r = l + 1if (l < a.length && this.less(a[l], a[m])) m = l
if (r < a.length && this.less(a[r], a[m])) m = r
if (m === i) return
;[a[i], a[m]] = [a[m], a[i]]
i = m
}
}
}
The array is public, as items, so that the lessons can print it. Code blocks follow the convention set out in the first chapter. Later files start with import { Heap } from './heap.ts'.
Buckets need no class. If the values are whole numbers from 0 to m - 1, make an array counts of m slots and add one to counts[v] for every value v: n steps, no comparisons between values. Then walk from slot m - 1 downwards, collecting values until you have k. It breaks down when the range is large: values up to 10^12 would need 1 lakh crore slots.
Quickselect borrows the partition step from quicksort: rearrange the array around a pivot value so that smaller values come before it and the rest after it, which leaves the pivot at its final sorted index p. If p is the index you want, stop. Otherwise the target lies on one side, and the other side is never touched again. If every pivot halved the range the work would be n + n/2 + n/4 + ..., less than 2n, and random pivots come close to that for an extreme rank such as the top five: one run below uses about 1.4 n comparisons, and twenty other seeds averaged about 1.8 n. The last lesson of this chapter gives the code and the inputs that make it slow.
Counting the work
The run draws 10 lakh scores between 0 and 9,99,999 from a seeded generator and asks each method for the five largest, counting comparisons between values (for buckets, increments plus slots visited). The quickselect function comes from qs.ts, whose code is in the last lesson of this chapter.
ts
function bySort(xs: number[], k: number) {
let cmp = 0const sorted = xs.toSorted((a, b) => {
cmp++
return b - a
})
return { top: sorted.slice(0, k), work: cmp }
}
ts
function byHeap(xs: number[], k: number) {
let cmp = 0const heap = new Heap<number>((a, b) => {
cmp++
return a < b
})
for (const x of xs) {
if (heap.size < k) heap.push(x)
else {
cmp++
if (x > (heap.peek() as number)) {
heap.pop()
heap.push(x)
}
}
}
return { top: heap.items.toSorted((a, b) => b - a), work: cmp }
}
ts
function byBuckets(xs: number[], k: number, maxValue: number) {
const counts = new Array<number>(maxValue + 1).fill(0)
for (const x of xs) counts[x]++
let steps = xs.length
const top: number[] = []
for (let v = maxValue; v >= 0 && top.length < k; v--) {
steps++
for (let c = 0; c < counts[v] && top.length < k; c++) top.push(v)
}
return { top, work: steps }
}
ts
function bySelect(xs: number[], k: number) {
const a = xs.slice()
const stats = { cmp: 0 }
const r = mulberry32(99)
const pick = (lo: number, hi: number) =>
lo + Math.floor(r() * (hi - lo + 1))
quickselect(a, a.length - k, pick, stats)
const top = a.slice(a.length - k).sort((x, y) => y - x)
return { top, work: stats.cmp }
}
Output of one run on Node 24; every line comes from the same data
All four methods return the same five values. The sort needed 1,86,05,817 comparisons, about 1.86 crore, close to n log2 n. The heap needed 10,00,258: 9,99,995 of them were the one comparison each value makes with the root, and only 263 happened inside the heap. Buckets took 10,00,004 steps, the 10 lakh increments plus four slots read. Quickselect used 14,06,388, about 1.4 per value.
On rising input every value beats the root, so every value costs a pop and a push. That is the heap's worst case: 46,66,647 comparisons, still O(n log k) with only five values held.
You need the 5 largest of 10 lakh values read from a file one at a time. What do you keep, and why a min-heap rather than a max-heap?
Keep a heap of at most 5 values. A min-heap puts the smallest kept value at the root: the one a new value must beat, and the one to remove when it does.
Which input makes the size-k heap do the most work, and what does it cost?
Rising order: every new value beats the root and causes a pop and a push. In the run that cost 46,66,647 comparisons, against 10,00,258 for random order.
Bucket counts handle 1 crore exam marks between 0 and 100 easily. Why not values up to 10^12?
The counts array needs a slot per possible value, so 1 lakh crore slots. Bucket counting costs O(m) space for m possible values, so it only fits a small range.
Part 2 · The kth largest sale of the day
The problem
A shop's billing screen shows the third largest order of the day so far and updates it after every order. That value is the kth largest: sort the orders from largest to smallest and take the item at position k. Equal values count separately, so among the orders 7, 7 and 7 the second largest is 7. Until k orders have arrived there is nothing to show, so the answer is undefined.
The obvious method keeps every order and sorts after each new one. Each sort costs about n log n comparisons, and a day with n orders pays that n times, which grows like n^2 log n. The run at the end of this lesson counts it: 2,000 orders cost the re-sorting method 1,78,70,497 comparisons.
The way out is an observation. The kth largest depends only on the k largest values. Every smaller value can be forgotten for good, because a later order can never move it back into the top k: values only arrive, none leave. The size-k heap of the previous lesson holds exactly the k largest, and its root, the smallest of them, is the kth largest.
How the heap answers it
Keep a min-heap with at most k values. For each new order:
if the heap has fewer than k values, push the order;
otherwise, if the order is larger than the root, pop the root and push the order;
otherwise ignore the order;
report the root if the heap now holds k values, and undefined if it does not.
The root is the right answer because the heap holds the k largest values so far and the root is the smallest of them: exactly k - 1 values are at least as large as it, so it sits at position k in the sorted order. Ties cause no trouble. A new order equal to the root is not larger, so it is ignored, and the kth largest value does not change, because the heap already holds k values at least that large.
Three small cases are worth keeping in mind. With k = 1 the heap holds one value and the answer is the running maximum. While fewer than k orders have arrived the answer is undefined. And the one-shot version of the problem, the kth largest of a whole array, is the same loop over the array followed by a look at the root.
Each add costs O(log k) at worst and O(1) when the order is rejected, and the memory is O(k), however many orders the day brings.
The code
The class below wraps the heap. Its file starts with import { Heap } from './heap.ts'.
ts
exportclass KthLargest {
k: number
heap = new Heap<number>((a, b) => a < b)
constructor(k: number) {
this.k = k
}
// Adds one order value; returns the kth largest so far, or undefined// while fewer than k values have arrived.
add(x: number): number | undefined {
if (this.heap.size < this.k) this.heap.push(x)
elseif (x > (this.heap.peek() as number)) {
this.heap.pop()
this.heap.push(x)
}
returnthis.heap.size === this.k ? this.heap.peek() : undefined
}
}
To check each answer, the demo also keeps every order and re-sorts, with the small function below, and prints ok when the two agree.
ts
exportfunction kthByResorting(seen: number[], k: number) {
if (seen.length < k) returnundefinedreturn seen.toSorted((a, b) => b - a)[k - 1]
}
ts
const orders = [1840, 560, 2250, 990, 3100, 1275, 450, 2780]
const board = new KthLargest(3)
const seen: number[] = []
for (const value of orders) {
seen.push(value)
const fast = board.add(value)
const slow = kthByResorting(seen, 3)
const verdict = fast === slow ? 'ok' : 'MISMATCH'const shown = String(value).padStart(5)
console.log(shown, '3rd largest:', fast ?? '-', verdict)
}
text
1840 3rd largest: - ok
560 3rd largest: - ok
2250 3rd largest: 560 ok
990 3rd largest: 990 ok
3100 3rd largest: 1840 ok
1275 3rd largest: 1840 ok
450 3rd largest: 1840 ok
2780 3rd largest: 2250 ok
Output of one run
After the third order the heap holds 1840, 560 and 2250, so the root 560 is the third largest. The fourth order, 990, beats the root: 560 leaves and the heap holds 990, 1840 and 2250. The fifth order, 3100, makes 990 leave and 1840 the new root. The orders 1275 and 450 are below the root and are ignored, so the answer stays 1840.
Checking it, and the cost
The tests cover the edges (fewer than k values, k = 1, equal values) and compare against re-sorting on 300 random streams.
ts
test('undefined until k values have arrived', () => {
const b = new KthLargest(3)
assert.equal(b.add(10), undefined)
assert.equal(b.add(20), undefined)
assert.equal(b.add(5), 5)
})
test('k = 1 is the running maximum', () => {
const b = new KthLargest(1)
const got = [3, 9, 4, 12, 1].map((x) => b.add(x))
assert.deepEqual(got, [3, 9, 9, 12, 12])
})
test('equal values count separately', () => {
const b = new KthLargest(2)
const got = [7, 7, 7, 8].map((x) => b.add(x))
assert.deepEqual(got, [undefined, 7, 7, 7])
})
ts
test('matches re-sorting on 300 random streams', () => {
const rand = mulberry32(5)
for (let t = 0; t < 300; t++) {
const k = 1 + Math.floor(rand() * 6)
const b = new KthLargest(k)
const seen: number[] = []
for (let i = 0; i < 40; i++) {
const x = Math.floor(rand() * 50)
seen.push(x)
assert.equal(b.add(x), kthByResorting(seen, k))
}
}
})
text
✔ undefined until k values have arrived (0.9492ms)
✔ k = 1 is the running maximum (0.8592ms)
✔ equal values count separately (0.2509ms)
✔ matches re-sorting on 300 random streams (15.797ms)
ℹ tests 4
ℹ pass 4
ℹ fail 0
Output of one run, excerpt; the millisecond figures vary
Now the cost. This run feeds 2,000 random orders to both methods with k = 10 and counts comparisons.
ts
const rand = mulberry32(31)
const orders = Array.from({ length: 2000 }, () =>
100 + Math.floor(rand() * 9900),
)
const k = 10let resort = 0const seen: number[] = []
for (const x of orders) {
seen.push(x)
seen.toSorted((a, b) => {
resort++
return b - a
})
}
ts
let heapCmp = 0const heap = new Heap<number>((a, b) => {
heapCmp++
return a < b
})
for (const x of orders) {
if (heap.size < k) heap.push(x)
else {
heapCmp++
if (x > (heap.peek() as number)) {
heap.pop()
heap.push(x)
}
}
}
ts
console.log('re-sort after every order:', resort, 'comparisons')
console.log('size-k heap:', heapCmp, 'comparisons')
text
re-sort after every order: 17870497 comparisons
size-k heap: 2395 comparisons
Output of one run
The heap needed 2,395 comparisons for the whole day, about one per order plus a few inside the heap. Re-sorting needed 1,78,70,497, thousands of times more, and the gap widens as the day grows.
The orders so far are 12, 40 and 25, and k = 2. What does the heap hold and what is reported? Then the order 40 arrives again.
The heap holds 40 and 25, and the root 25 is reported as the 2nd largest.
The second 40 is larger than the root 25, so 25 leaves, the heap holds 40 and 40, and 40 is reported: equal values count separately.
Why does the heap solution use O(k) memory while re-sorting uses O(n)?
The kth largest depends only on the k largest values, so everything smaller is discarded as soon as it is out of the top k. Re-sorting keeps every order.
What should add return while fewer than k orders have arrived, and how does the class know?
It returns undefined. The heap size is below k, which means no kth largest exists yet.
Part 3 · The nearest charging stations
The problem
A delivery van needs the k nearest charging stations. Stations sit at points on a map of kilometres, the van is at another point, and distance is the straight line between them. The answer is the k stations with the smallest distance, nearest first.
This is the same top k question as before with a different ordering: smaller is better. A city map can list lakhs of stations, and the van asks again every few seconds as it moves, so sorting every station on every question is wasteful.
One detail first. The distance from (x1, y1) to (x2, y2) is the square root of dx^2 + dy^2, where dx and dy are the differences. A larger number always has a larger square root, so ordering by the squared distance gives the same order as ordering by distance. Skipping the square root is faster, and with whole-number coordinates the squared distance is an exact whole number, with no rounding error to cause false ties.
Keep the k smallest with a max-heap
For the k largest the root of the heap held the weakest value kept: the smallest. For the k nearest, the weakest value kept is the farthest of them, so the heap is a max-heap on distance, with the farthest kept station at the root. That is a mirror image of the previous lesson.
Question
Heap
Root holds
A newcomer replaces the root when
k largest
min-heap
the smallest kept value
it is larger than the root
k smallest or nearest
max-heap
the largest kept distance
it is smaller than the root
k largest
Heapmin-heap
Root holdsthe smallest kept value
A newcomer replaces the root whenit is larger than the root
k smallest or nearest
Heapmax-heap
Root holdsthe largest kept distance
A newcomer replaces the root whenit is smaller than the root
The loop is unchanged. Push stations until the heap holds k. After that, compare each station's squared distance with the root's. If it is smaller, pop the root and push the station. Afterwards the heap holds the k nearest stations in no particular order, so sort those k at the end: O(k log k), which is small next to the O(n log k) scan.
The same correctness argument applies with the order reversed. A discarded station is no nearer than the root, and the heap already holds k stations at least as near as the root, so the discarded one cannot be among the k nearest. A station nearer than the root joins the heap's k, and the farthest of the k + 1 is the root, which is removed.
Ties need a decision. If three stations are equally near and only two fit, the problem does not say which two, so which two it keeps depends on the order of arrival and on the heap's inner layout, and the code makes no promise about it. The checks therefore compare distances, not station names.
The code
The distance function takes a station and the van's position. The heap's less function returns true when its first argument is farther away, which makes the farthest station the root.
ts
exportinterface Station {
id: string
x: number
y: number
}
exportinterface Spot {
x: number
y: number
}
exportfunction d2(s: Station, car: Spot): number {
return (s.x - car.x) ** 2 + (s.y - car.y) ** 2
}
// The k stations nearest to the car, nearest first.exportfunction nearest(
stations: Station[], car: Spot, k: number,
): Station[] {
// A max-heap on distance: the farthest kept station is on top.const kept = new Heap<Station>((a, b) => d2(a, car) > d2(b, car))
for (const s of stations) {
if (kept.size < k) kept.push(s)
elseif (d2(s, car) < d2(kept.peek() as Station, car)) {
kept.pop()
kept.push(s)
}
}
return kept.items.toSorted((a, b) => d2(a, car) - d2(b, car))
}
Old Market squared distance 13
Mill Lane squared distance 13
Fort Gate squared distance 25
Output of one run
The three nearest stations to a van at (0, 0) are Old Market and Mill Lane, tied at squared distance 13, and Fort Gate at 25. With a tie, either order of the first two is correct.
Checking it
The tests cover k larger than the list, a tie at the boundary, and 500 random lists with coordinates from a small range so that many stations tie. The reference is a full sort of the distances.
test('same distances as a full sort on 500 random lists', () => {
const rand = mulberry32(21)
const car = { x: 2, y: 3 }
for (let t = 0; t < 500; t++) {
const n = 1 + Math.floor(rand() * 30)
const k = 1 + Math.floor(rand() * 8)
const coord = () => Math.floor(rand() * 11) - 5const list = Array.from({ length: n }, (_, i) => ({
id: 's' + i,
x: coord(),
y: coord(),
}))
const all = list.map((s) => d2(s, car)).sort((a, b) => a - b)
const want = all.slice(0, k)
assert.deepEqual(nearest(list, car, k).map((s) => d2(s, car)), want)
}
})
text
✔ k larger than the list returns everything, nearest first (1.5032ms)
✔ ties at the boundary keep the right distances (0.1896ms)
✔ same distances as a full sort on 500 random lists (8.5437ms)
ℹ tests 3
ℹ pass 3
ℹ fail 0
Output of one run, excerpt; the millisecond figures vary
Each station is read once, and a station is kept only if it beats the root, so the cost is O(n log k) time and O(k) space. For the 10 stations of a small town that hardly matters; for a few lakh stations queried repeatedly it does.
Why can the code compare squared distances instead of distances?
The square root is increasing, so a larger squared distance always means a larger distance and the order is the same. It avoids square roots and, with whole-number coordinates, avoids rounding.
To find the k nearest stations, why is the heap a max-heap and not a min-heap?
The root must be the kept station that a newcomer has to beat, which is the farthest one. A max-heap on distance puts the farthest at the root.
Four stations lie at squared distances 4, 9, 9 and 16 and k = 2. Which distances should a correct answer report?
4 and 9. Either station at distance 9 may be reported; the problem does not break the tie, so tests compare distances.
Part 4 · The most searched terms
The problem
A shopping site logs every search term. The home page shows the k most searched terms of the day, most searched first. There are two stages: count how often each term appears, then pick the k terms with the largest counts.
Counting is the easy part. One pass over the log with a hash map from term to count costs O(n) for n searches, and the map holds one entry for each of the m distinct terms. The second stage is a top k question over those m entries, and the log is usually far longer than the list of distinct terms.
Before choosing a method, fix the tie rule, because two terms often share a count. Here a higher count comes first and equal counts go in alphabetical order. Without a rule, two correct solutions can return different lists, and a test can only compare answers that the problem pins down.
Two ways to pick the top k
With a heap. Keep a min-heap of at most k entries, each a term with its count. The root is the weakest entry, meaning the lowest count or, at equal counts, the alphabetically later term. A new entry replaces the root if it is stronger. This costs O(n) to count plus O(m log k) to select.
With buckets. A count is a whole number between 1 and n, so counts can index an array. Make an array of n + 1 lists, put each term into the list at its count, then read the lists from the highest count downwards until k terms are collected. No comparisons between counts are needed, and the total is O(n), plus the sorting of tied terms inside a list.
Method
Time
Extra space
Notes
Heap of size k
O(n + m log k)
O(m) for the counts, O(k) for the heap
Works for any ordering, and can keep up with a growing log
Buckets by count
O(n) plus tie sorting
O(n)
Needs whole-number counts; ties come out in list order unless sorted
Heap of size k
TimeO(n + m log k)
Extra spaceO(m) for the counts, O(k) for the heap
NotesWorks for any ordering, and can keep up with a growing log
Buckets by count
TimeO(n) plus tie sorting
Extra spaceO(n)
NotesNeeds whole-number counts; ties come out in list order unless sorted
The tie rule matters most for buckets. Terms enter a bucket in the order the map lists them, which is the order they first appeared, because a JavaScript Map remembers insertion order (see Map on MDN). That order is not alphabetical, so the buckets must be sorted wherever a tie could cut the list at k.
The code
Both methods start from the same counting function.
ts
exporttype Entry = [term: string, count: number]
exportfunction countTerms(log: string[]): Map<string, number> {
const counts = new Map<string, number>()
for (const term of log) counts.set(term, (counts.get(term) ?? 0) + 1)
return counts
}
The heap version defines weaker for the tie rule and keeps the k strongest entries. The final toSorted puts the strongest first.
ts
// Ranking: higher count first; equal counts, alphabetical order.const weaker = (a: Entry, b: Entry) =>
a[1] < b[1] || (a[1] === b[1] && a[0] > b[0])
exportfunction topByHeap(log: string[], k: number): string[] {
const kept = new Heap<Entry>(weaker)
for (const e of countTerms(log)) {
if (kept.size < k) kept.push(e)
elseif (weaker(kept.peek() as Entry, e)) {
kept.pop()
kept.push(e)
}
}
const best = kept.items.toSorted((a, b) => (weaker(a, b) ? 1 : -1))
return best.map((e) => e[0])
}
The bucket version has a switch, tidy, that turns the sorting of tied terms off so the tie order can be seen.
ts
exportfunction topByBuckets(
log: string[], k: number, tidy = true,
): string[] {
const size = log.length + 1const buckets: string[][] = Array.from({ length: size }, () => [])
for (const [term, c] of countTerms(log)) buckets[c].push(term)
const out: string[] = []
for (let c = log.length; c >= 1 && out.length < k; c--) {
const same = tidy ? buckets[c].toSorted() : buckets[c]
for (const term of same) if (out.length < k) out.push(term)
}
return out
}
Running it
The demo uses a log of 13 searches. Gumboots and diya both have two searches, so the tie decides which of them takes the fourth place.
Both methods agree, and put diya before gumboots because d sorts before g. The raw bucket order, with tidying off, puts gumboots first, because gumboots was searched before diya. Both are valid answers to a question without a tie rule. The rule makes the answer unique.
ts
function byFullSort(log: string[], k: number): string[] {
return [...countTerms(log)]
.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
.slice(0, k)
.map((e) => e[0])
}
test('k larger than the distinct terms returns them all', () => {
assert.deepEqual(topByHeap(['b', 'a', 'b'], 9), ['b', 'a'])
assert.deepEqual(topByBuckets(['b', 'a', 'b'], 9), ['b', 'a'])
})
test('both methods agree with a full sort on 400 random logs', () => {
const rand = mulberry32(3)
const words = ['ant', 'bee', 'cat', 'dog', 'eel', 'fox', 'gnu', 'hen']
for (let t = 0; t < 400; t++) {
const n = 1 + Math.floor(rand() * 40)
const log = Array.from({ length: n }, () => {
return words[Math.floor(rand() * words.length)]
})
const k = 1 + Math.floor(rand() * 6)
assert.deepEqual(topByHeap(log, k), byFullSort(log, k))
assert.deepEqual(topByBuckets(log, k), byFullSort(log, k))
}
})
text
✔ k larger than the distinct terms returns them all (1.635ms)
✔ both methods agree with a full sort on 400 random logs (10.0615ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0
Output of one run, excerpt; the millisecond figures vary
The random test uses a vocabulary of eight words, so ties are frequent, and compares both methods with a full sort under the same rule.
The log has 1 lakh searches and 8,000 distinct terms, and you want the top 10. What does the heap method cost?
Counting costs O(n) with n = 1 lakh. Selecting costs O(m log k) with m = 8,000 and k = 10, so each of the 8,000 counts costs a comparison and, rarely, a few heap steps.
Why are bucket indexes counts rather than terms?
Counts are whole numbers from 1 to n, so they can index an array directly, and reading the array from the top gives terms in order of count with no comparisons.
Why must the problem state a tie rule, and what happens to the bucket method without one?
Equal counts have no natural order, so different correct methods can return different lists. Without sorting, the bucket method returns tied terms in the order they were first seen.
Part 5 · Spacing out task labels
The problem
A shelf-labelling robot must place labels in a row so that no two equal labels are next to each other, since soap soap looks like a misprint. Given the labels, return an order with no equal neighbours, or report that none exists.
Whether an order exists is settled by one number. Suppose a label occurs c times among n positions. Its copies must be separated, so at least c - 1 other labels sit between them, and the row has at least c + (c - 1) positions. So c <= (n + 1) / 2, which for whole numbers is c <= ceil(n / 2). That is a necessary condition for the most frequent label, and the next page shows it is also enough.
This idea suggests the method: the most frequent label is the hardest to place, so place it first whenever it is allowed. A max-heap on the number of copies left gives the label to place next.
The greedy rule, and why it never gets stuck
Fill the row from left to right. At each position, place a label with the most copies left among the labels different from the one just placed. With a heap, pop the top, place it, hold it out for one step so it cannot come straight back, then push it back with one fewer copy.
Proof that this works whenever c <= ceil(n / 2) for every label. Let m be the positions still to fill, c(y) the copies of label y left, and x the label just placed (none at the start). Call the state good if c(y) <= ceil(m / 2) for every y other than x, and c(x) <= floor(m / 2). The start is good under the condition above. From a good state with m >= 1:
Some label other than x has copies left: if only x did, then c(x) = m, which is more than floor(m / 2).
Greedy places z, the label other than x with the most copies. Afterwards c(z) - 1 <= ceil(m / 2) - 1 = floor((m - 1) / 2), the bound the label just placed must meet.
The old x is now an ordinary label, and c(x) <= floor(m / 2) = ceil((m - 1) / 2), so it meets the bound.
Any other y has c(y) <= c(z) <= ceil(m / 2). The new bound ceil((m - 1) / 2) is smaller only when m is odd, and then c(y) = (m + 1) / 2 would make y and z together hold m + 1 copies, more than the m left. So c(y) meets the new bound.
So the state after each placement is good, the greedy never runs out of choices, and the row gets filled. The proof used only c(y) <= c(z), so any tie between equally frequent labels may be broken either way.
The code
Both functions share a small counting helper and an entry type.
ts
type Entry = [label: string, count: number]
function tally(labels: string[]): Map<string, number> {
const counts = new Map<string, number>()
for (const l of labels) counts.set(l, (counts.get(l) ?? 0) + 1)
return counts
}
The heap holds a label with its copies left, with the most copies on top and, at equal counts, the alphabetically earlier label, so that runs are repeatable. resting is the label placed in the previous step.
ts
// Most copies left first; equal counts, alphabetical.const moreLeft = (a: Entry, b: Entry) =>
a[1] > b[1] || (a[1] === b[1] && a[0] < b[0])
// An order with no equal neighbours, or null if none exists.exportfunction spaceOut(labels: string[]): string[] | null {
const heap = new Heap<Entry>(moreLeft)
for (const e of tally(labels)) heap.push(e)
const out: string[] = []
let resting: Entry | null = null// placed last step, held outwhile (heap.size > 0 || resting) {
const top = heap.pop()
if (!top) returnnull// only the label we just placed is left
out.push(top[0])
if (resting) heap.push(resting)
resting = top[1] > 1 ? [top[0], top[1] - 1] : null
}
return out
}
The feasibility test is the condition that was proved necessary and sufficient. If the condition holds the greedy loop finishes; if it fails, the loop reaches a point where only the resting label is left and returns null.
ts
// The condition the proof above shows is exactly right.exportfunction canSpace(labels: string[]): boolean {
const most = Math.max(0, ...tally(labels).values())
return most <= Math.ceil(labels.length / 2)
}
soap salt soap tea oil salt soap tea
feasible true
null feasible false
Output of one run
The first shelf has eight labels with soap three times, and the order has no equal neighbours. The second has soap three times among four labels, more than ceil(4 / 2) = 2, so the function reports null.
A cooldown variant
A packing line runs one task per time slot. The same kind of task may not run again until cooldown slots have passed, though idle slots are allowed. What is the fewest slots needed for all tasks? A cooldown of 1 is the problem above, with idle slots instead of impossible orders.
A lower bound holds for every schedule. Let m be the highest number of copies of any label and t the number of labels with m copies. The first copy of such a label can go in slot 1, but each later copy is at least cooldown + 1 slots after the one before, so the last copy is in a slot no earlier than 1 + (m - 1)(cooldown + 1). The t labels each have a last copy, in different slots, so the last of them is no earlier than (m - 1)(cooldown + 1) + t. Every task also needs its own slot, so the answer is at least the number of tasks.
ts
// Fewest time slots to run every task when two runs of the same label// need at least `cooldown` slots between them. Idle slots are allowed.exportfunction leastTime(tasks: string[], cooldown: number): number {
// Copies left, most first.const heap = new Heap<number>((a, b) => a > b)
for (const c of tally(tasks).values()) heap.push(c)
const waiting: { readyAt: number; left: number }[] = []
let head = 0let time = 0while (heap.size > 0 || head < waiting.length) {
time++
while (head < waiting.length && waiting[head].readyAt <= time) {
heap.push(waiting[head++].left)
}
const left = heap.pop()
if (left !== undefined && left > 1) {
waiting.push({ readyAt: time + cooldown + 1, left: left - 1 })
}
}
return time
}
ts
// A lower bound that holds for every valid schedule.exportfunction lowerBound(tasks: string[], cooldown: number): number {
const counts = [...tally(tasks).values()]
const m = Math.max(0, ...counts)
const t = counts.filter((c) => c === m).length
return Math.max(tasks.length, (m - 1) * (cooldown + 1) + t)
}
The simulation runs, in each slot, the label with the most copies left among those out of cooldown, and an unused slot is idle. It matches the bound on these four cooldowns. This lesson does not prove that the simulation reaches the bound for every input. The bound is proved above; the match is checked exhaustively below for small cases.
Checking it
The first test runs 2,000 random lists and checks three things: the output is a rearrangement of the input with no equal neighbours whenever the condition holds, and the result is null whenever it fails. The second compares the simulation and the bound with an exhaustive search, which tries every choice of label or idle slot, on every pattern of up to three labels with at most four copies each and cooldowns from 0 to 3.
ts
function isValid(out: string[], labels: string[]): boolean {
const same = out.toSorted().join() === labels.toSorted().join()
return same && out.every((x, i) => i === 0 || x !== out[i - 1])
}
test('spaceOut is valid, or null when the condition fails', () => {
const rand = mulberry32(8)
const pool = ['a', 'b', 'c', 'd']
const pick = () => pool[Math.floor(rand() * 4 * rand())]
let yes = 0for (let t = 0; t < 2000; t++) {
const n = 1 + Math.floor(rand() * 12)
const labels = Array.from({ length: n }, pick)
const out = spaceOut(labels)
if (canSpace(labels)) {
assert.ok(out && isValid(out, labels))
yes++
} else assert.equal(out, null)
}
console.log('arranged', yes, 'of 2000 lists; the rest gave null')
})
ts
// Exhaustive search: can `counts` copies be run in `slots` slots?function fits(
counts: number[], cooldown: number, slots: number,
): boolean {
const left = counts.slice()
const last = counts.map(() => -Infinity)
const go = (slot: number, todo: number): boolean => {
if (todo === 0) returntrueif (slot === slots || todo > slots - slot) returnfalsefor (let i = 0; i < left.length; i++) {
if (left[i] > 0 && slot - last[i] > cooldown) {
const before = last[i]
left[i]--
last[i] = slot
const ok = go(slot + 1, todo - 1)
left[i]++
last[i] = before
if (ok) returntrue
}
}
return go(slot + 1, todo) // an idle slot
}
return go(0, counts.reduce((a, b) => a + b, 0))
}
ts
function bruteLeast(counts: number[], cooldown: number): number {
let slots = counts.reduce((a, b) => a + b, 0)
while (!fits(counts, cooldown, slots)) slots++
return slots
}
ts
test('leastTime equals the exhaustive answer; the bound is met', () => {
let cases = 0for (let a = 1; a <= 4; a++)
for (let b = 0; b <= a; b++)
for (let c = 0; c <= b; c++) {
for (let cooldown = 0; cooldown <= 3; cooldown++) {
const counts = [a, b, c].filter((x) => x > 0)
const tasks = counts.flatMap((n, i) => {
return Array<string>(n).fill('LMN'[i])
})
const want = bruteLeast(counts, cooldown)
assert.equal(leastTime(tasks, cooldown), want)
assert.equal(lowerBound(tasks, cooldown), want)
cases++
}
}
console.log('exhaustive check:', cases, 'cases')
})
text
arranged 1075 of 2000 lists; the rest gave null
exhaustive check: 136 cases
✔ spaceOut is valid, or null when the condition fails (15.4479ms)
✔ leastTime equals the exhaustive answer; the bound is met (3.9445ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0
Output of one run, excerpt; the millisecond figures vary
Of the 2,000 random lists, 1,075 could be arranged and the rest gave null, so both branches were exercised. The exhaustive check covered 136 cases, and in every one the simulation, the bound and the exhaustive search gave the same number of slots. The search is slow and only for checking; the method itself does not need it.
Can the labels a, a, a, b, c be placed with no two a's adjacent? And a, a, a, a, b, c?
Yes for the first: a b a c a. 3 <= ceil(5 / 2) = 3.
No for the second: 4 > ceil(6 / 2) = 3, and the greedy returns null.
Why does the greedy hold the label it just placed out of the heap for one step?
Otherwise the label with the most copies left would be popped again straight away and placed next to itself. Holding it out guarantees a different label comes next.
With a cooldown of 2, the tasks are A, A, A, A, B, C. What is the lower bound and a schedule that reaches it?
m = 4 copies of A and t = 1 label with that count, so (4 - 1)(2 + 1) + 1 = 10, and there are 6 tasks, so the bound is 10. The schedule A B C A idle idle A idle idle A reaches it.
Part 6 · Fewest distinct products after k removals
The problem
A stockroom audit removes exactly k items from a shelf, and the aim is to leave as few different products as possible on the shelf. The shelf holds n items and some products appear many times. Which k items should go?
Take the shelf rice, dal, dal, oil, oil, oil, salt, tea, tea, rice, soap. Counting gives rice 2, dal 2, oil 3, salt 1, tea 2 and soap 1. Removing salt and soap, one item each, makes two products disappear for two removals. Removing the three oils makes only one disappear for three. Products with few items are cheap to wipe out, so the plan is to wipe out the cheapest products first.
This is a greedy choice, so it needs a proof, not only a test. The next page gives one.
Why the cheapest products first is right
Let the counts, sorted from smallest, be c1 <= c2 <= ... <= cm. A removal plan makes some set E of products disappear, which means removing every item of each product in E. That costs at least the sum of the counts in E, and the sum of the counts of any e products is at least c1 + ... + ce, the sum of the e smallest. So making e products disappear needs k >= c1 + ... + ce.
Let e be the largest number with c1 + ... + ce <= k. No plan can wipe out more than e products. And e is reachable: remove all items of the e cheapest products, which costs S = c1 + ... + ce <= k removals. The k - S removals still to make are fewer than the next count c(e+1), because e is the largest, so they can be taken from the products that remain without emptying any of them. The shelf then holds m - e products, the fewest possible.
The algorithm follows: go through the counts from smallest, subtract each from the budget k while it fits, and count how many products were wiped out. Sorting the counts does this directly. A min-heap of counts does the same without sorting everything: pop the smallest while it is at most the budget.
The code
Both versions take the shelf as a list of product names and the number k, which must not exceed the number of items. The sorted version walks the counts and stops at the first one that no longer fits.
The counting helper returns one count per product.
ts
function countsOf(items: string[]): number[] {
const counts = new Map<string, number>()
for (const p of items) counts.set(p, (counts.get(p) ?? 0) + 1)
return [...counts.values()]
}
ts
// Fewest distinct products left after removing exactly k items.exportfunction fewestDistinct(items: string[], k: number): number {
const counts = countsOf(items).sort((a, b) => a - b)
let budget = k
let left = counts.length
for (const c of counts) {
if (c > budget) break
budget -= c
left--
}
return left
}
ts
exportfunction fewestDistinctHeap(items: string[], k: number): number {
const rare = new Heap<number>((a, b) => a < b)
for (const c of countsOf(items)) rare.push(c)
let budget = k
while (rare.size > 0 && (rare.peek() as number) <= budget) {
budget -= rare.pop() as number
}
return rare.size
}
The brute-force reference tries every way of choosing which k items to remove. It is only feasible for small shelves, which is all the test needs.
ts
// Tries every way to pick k of the n items to remove.exportfunction bruteDistinct(items: string[], k: number): number {
let best = Infinity
const gone = new Array<boolean>(items.length).fill(false)
const go = (from: number, left: number) => {
if (left === 0) {
const kept = items.filter((_, i) => !gone[i])
best = Math.min(best, new Set(kept).size)
return
}
for (let i = from; i <= items.length - left; i++) {
gone[i] = true
go(i + 1, left - 1)
gone[i] = false
}
}
go(0, k)
return best
}
Running it
ts
const shelf = [
'rice', 'dal', 'dal', 'oil', 'oil', 'oil',
'salt', 'tea', 'tea', 'rice', 'soap',
]
// counts: rice 2, dal 2, oil 3, salt 1, tea 2, soap 1for (const k of [0, 1, 2, 3, 5, 7, 11]) {
const a = fewestDistinct(shelf, k)
const b = fewestDistinctHeap(shelf, k)
console.log('remove', String(k).padStart(2), '-> distinct left', a, b)
}
text
remove 0 -> distinct left 66
remove 1 -> distinct left 55
remove 2 -> distinct left 44
remove 3 -> distinct left 44
remove 5 -> distinct left 33
remove 7 -> distinct left 22
remove 11 -> distinct left 00
Output of one run; the two numbers are the sorted and heap answers
With k = 3, salt and soap take two removals, and the remaining one cannot wipe out any product that has two or more items, so four products stay. With k = 7 the counts 1, 1, 2 and 2 cost 6, which leaves oil and one product with two items, and the seventh removal comes from one of them. With k = 11 everything goes.
test('same answer as trying every removal, 600 random shelves', () => {
const rand = mulberry32(12)
for (let t = 0; t < 600; t++) {
const n = 1 + Math.floor(rand() * 9)
const items = Array.from({ length: n }, () => {
return'p' + Math.floor(rand() * 5)
})
const k = Math.floor(rand() * (n + 1))
const want = bruteDistinct(items, k)
assert.equal(fewestDistinct(items, k), want)
assert.equal(fewestDistinctHeap(items, k), want)
}
})
text
✔ removing nothing, or everything (0.6018ms)
✔ the leftover removals never empty another product (0.0929ms)
✔ same answer as trying every removal, 600 random shelves (6.6731ms)
ℹ tests 3
ℹ pass 3
ℹ fail 0
Output of one run, excerpt; the millisecond figures vary
The third test compares both versions with the exhaustive search on 600 random shelves of up to nine items. Both take O(n) to count and O(m log m) to sort or to build the heap for m distinct products.
Counts are 1, 2, 2, 5 and k = 4. How many products can be wiped out, and what is left?
1 and 2 cost 3, and the next count 2 does not fit in the remaining budget of 1. So two products disappear, and the one leftover removal comes from another product that keeps at least one item. Two products remain.
Why is it enough to look at the sum of the e smallest counts?
Any set of e products costs at least the sum of its counts, and the sum of the e smallest counts is the least possible sum for e products. If even that exceeds k, no plan wipes out e products.
What does the greedy do with removals it cannot use to wipe out a product?
It takes them from the products that remain. They are fewer than the next count, so no remaining product is emptied.
Part 7 · The kth largest with quickselect
Selection without sorting
The kth largest of an array of n values sits at index n - k once the array is sorted from smallest to largest. Quickselect finds the value for that index without sorting the rest. It works in place on an array that is already in memory, uses O(1) extra space apart from a loop, and takes O(n) time on average.
It uses the partition step of quicksort. Pick a pivot, then rearrange the cells so that every value smaller than the pivot comes before it and every other value after it. The pivot then sits at its final sorted index p, whatever the order of the other cells. Compare p with the target index. If they are equal, the pivot is the answer. If p is smaller, the answer lies in the cells after p, and if p is larger, in the cells before it. The other side is dropped, and the search repeats on what is left.
The partition used here is the Lomuto scheme. Move the pivot to the last cell. Keep a boundary i, starting at the first cell, so that everything before i is smaller than the pivot, and scan the other cells with j. When a[j] is smaller than the pivot, swap it into cell i and move i one step right. At the end, swap the pivot into cell i.
One partition, step by step
The scene finds the third largest of nine values, which belongs at index 6, and uses the last cell, 5, as the pivot. It follows the same Lomuto steps as the code on the next page.
Animated sceneOne partition step of quickselect0:30
The third largest of nine values belongs at index 6 once sorted
Read it as steps
one pass places the pivot, and the half that cannot hold the answer is dropped
The pivot landed at index 4, left of the target index 6, so the third largest is somewhere in cells 5 to 8, and cells 0 to 4 are never looked at again. The cost of the step was 8 comparisons, one per cell scanned. If the next pivot also halves the range, the next step costs about 4, then 2, and the total stays below twice the array length.
The code
The partition returns where the pivot landed. stats counts comparisons so that the lessons can report them. It uses a plain swap helper.
ts
exportinterface Stats {
cmp: number
}
function swap(a: number[], i: number, j: number): void {
const t = a[i]
a[i] = a[j]
a[j] = t
}
ts
// Lomuto partition: puts the pivot in its sorted place, returns where.exportfunction partition(
a: number[], lo: number, hi: number, pivotAt: number, stats: Stats,
): number {
swap(a, pivotAt, hi)
const pivot = a[hi]
let i = lo
for (let j = lo; j < hi; j++) {
stats.cmp++
if (a[j] < pivot) {
swap(a, i, j)
i++
}
}
swap(a, i, hi)
return i
}
The selection loop keeps the target index inside [lo, hi] at all times, and everything before lo is no larger than everything inside the range, which is no larger than everything after hi. Each partition keeps both facts, so when the range shrinks to one cell, that cell holds the answer.
ts
// Reorders a so that a[target] holds the value that belongs there when// sorted, with no larger value before it and no smaller one after it.exportfunction quickselect(
a: number[], target: number, pick: (lo: number, hi: number) => number,
stats: Stats = { cmp: 0 },
): number {
let lo = 0let hi = a.length - 1while (lo < hi) {
const p = partition(a, lo, hi, pick(lo, hi), stats)
if (p === target) return a[p]
if (p < target) lo = p + 1else hi = p - 1
}
return a[lo]
}
The pivot rule is a parameter. The wrapper below uses a random pivot from the seeded generator.
ts
// The kth largest value (k = 1 is the maximum). Reorders `a`.exportfunction kthLargest(
a: number[], k: number, rand: () => number,
): number {
const pick = (lo: number, hi: number) =>
lo + Math.floor(rand() * (hi - lo + 1))
return quickselect(a, a.length - k, pick)
}
ts
test('single element, and k equal to the length', () => {
const r = mulberry32(1)
assert.equal(kthLargest([42], 1, r), 42)
assert.equal(kthLargest([5, 3, 9, 1], 4, r), 1)
})
test('matches a full sort on 1000 random arrays with repeats', () => {
const r = mulberry32(77)
for (let t = 0; t < 1000; t++) {
const n = 1 + Math.floor(r() * 30)
const xs = Array.from({ length: n }, () => Math.floor(r() * 12))
const k = 1 + Math.floor(r() * n)
const want = xs.toSorted((a, b) => b - a)[k - 1]
assert.equal(kthLargest(xs.slice(), k, r), want)
}
})
text
✔ single element, and k equal to the length (0.7779ms)
✔ matches a full sort on 1000 random arrays with repeats (4.3369ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0
Output of one run, excerpt; the millisecond figures vary
Which pivot, and the bad cases
The expected O(n) cost rests on pivots that cut the range roughly in half. Take the first cell as the pivot and a sorted array defeats that: the first cell is the smallest value, it lands at the start, and the range shrinks by one cell per step, so the cost grows like n^2 / 2. The run counts comparisons for the 10th largest of 5,000 values under both pivot rules, on three inputs.
const n = 5000const k = 10const shuffled = Array.from({ length: n }, () =>
Math.floor(rand() * 1_000_000),
)
const rising = Array.from({ length: n }, (_, i) => i)
const equal = new Array<number>(n).fill(7)
const head = ['input'.padEnd(10), 'first-element'.padStart(14)]
console.log(...head, 'random'.padStart(10))
const inputs = { shuffled, rising, 'all equal': equal }
for (const [name, xs] of Object.entries(inputs)) {
const first = String(count(xs, k, firstPivot)).padStart(14)
const random = String(count(xs, k, randomPivot)).padStart(10)
console.log(name.padEnd(10), first, random)
}
text
input first-element random
shuffled 763116316
rising 124974647275
all equal 1249746412497464
Output of one run; the random column depends on the seed
On shuffled input the first-element rule needed 7,631 comparisons and the random rule 16,316. Both are a few times n, and neither is better in general, since a shuffled array has no order for the first cell to exploit. On input in rising order the first-element rule needed 1,24,97,464, close to 5,000 x 4,999 / 2 = 1,24,97,500, while the random pivot needed 7,275. The last row shows a weakness that no pivot rule of this kind fixes: when every value is equal, Lomuto sends every value to the same side and both rules take about n^2 / 2 steps. The usual repair is a three-way partition, into smaller, equal and larger parts, which this lesson does not build.
A method called median of medians chooses pivots so that the worst case is O(n) too, but its constant factor is large, and a random pivot is the usual choice in practice.
Related on LeetCode: Find the Kth Largest Integer in the Array. There the values are digit strings, so the partition would compare by length first and by text second.
The array is [9, 4, 7, 1] and you want the 2nd largest. Which index does quickselect aim for, and what is the answer?
Index n - k = 4 - 2 = 2 of the sorted array [1, 4, 7, 9]. The value there is 7.
Why does a first-element pivot take about n^2 / 2 steps on a sorted array?
The first cell is the smallest value, so the partition puts it at the start and the range only shrinks by one cell. The step costs n - 1, then n - 2, and so on, which adds up to about n^2 / 2.
When would you choose the size-k heap over quickselect?
When the values arrive as a stream, or are too many to hold in memory, or must not be reordered. The heap sees each value once and keeps only k.