awelgorithms

The heap holds the current top k

Updated

After the stream, the k slots are the k largest (min-heap of size k) or k smallest (max-heap of size k). Order inside the heap is not sorted.

What to focus on

During the stream, a[0] is the current k-th, not the overall max. Drain or scan the k slots at the end; do not assume a[1] is second-largest.

Worked examples

top 2 of three

a = [1, 4, 9], k = 2
  1. fill [1, 4]
  2. 9 replaces 1 → [4, 9]

Result: top 2 are 4 and 9

top 2 of four

a = [1, 4, 9, 7], k = 2
  1. after 9: [4, 9]
  2. 7 replaces 4 → [7, 9]

Result: top 2 are 7 and 9

top 1

a = [1, 4, 9], k = 1
  1. fill [1]
  2. 4 replaces 1
  3. 9 replaces 4

Result: top 1 is 9

Try it

Write topK(a, k). a is the stream. k is how many winners to keep. The heap is a min-heap of size k. parent(i) = Math.floor((i-1)/2). Return the k slots, unordered. Print the set. Do not sort the heap slots. [1, 4, 9] k=2 → {4, 9} [1, 4, 9, 7] k=2 → {7, 9} k=1 → {9}

k is 1–3. The stream has 3–6 integers. The heap is a min-heap of size k after fill.