Ch. 18 · Data Structures & Algorithms

Heaps for Top-K and Incremental Selection

Heaps for Top-K and Incremental Selection. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readintermediateupdated Oct 3, 2026

A bounded heap retains the best k candidates without sorting every item. Its root should represent the easiest retained item to replace.

Before you start

You should know arrays, loops and basic complexity notation. Start with a small input you can trace by hand. State what each variable means and which invariant is maintained, then use that invariant to explain correctness before discussing performance or writing a more compact solution.

The practical goal is to reason through this situation: A min-heap of size k keeps the k largest values while scanning. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Choose the retained set

Keep the k largest candidates seen so far.

Step 2: Use the correct root

A min-heap exposes the smallest retained value for replacement.

Step 3: Bound heap size

Insert until k, then replace only when the new value is larger.

Worked scenario

A min-heap of size k keeps the k largest values while scanning.

For k=2 and [5,1,9,3], retain 5 and 1 initially. Nine replaces 1; three is discarded because it is smaller than the retained minimum five. Work is O(n log k) with O(k) storage for positive k, subject to initialization and output-order requirements.

Common mistake

Using the wrong heap direction discards the desired extremes.

Verify the behavior

Test k=0, k greater than input size, ties and negative values.

Interview exercise

Analyze the method.

Answer and reasoning

Each insertion or replacement costs O(log k), giving O(n log k) time and O(k) working storage.

Continue learning

Compare the scenario with the Data Structures and Algorithms interview questions and test your understanding with the Data Structures and Algorithms MCQs. For terminology and implementation details, consult the reference material.

More in Data Structures & Algorithms

read ✓Data Structures & Algorithms · mid

Bit Manipulation Patterns for Interviews

Set, test and clear bits, exploit XOR properties, and count set bits with the Brian Kernighan trick.

~2 min readread →
read ✓Data Structures & Algorithms · hard

Backtracking and Safe Pruning Rules

Backtracking and Safe Pruning Rules. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
read ✓Data Structures & Algorithms · easy

Big-O Complexity and Input Growth

Big-O Complexity and Input Growth. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc