Heap Interview Questions 2026

Heaps unlock a class of problems that cannot be solved efficiently with sorting alone: streaming top-K, continuous median, and multi-source merging.

Top-K Pattern

Find the K largest elements: use a min-heap of size K. For each element, if it is larger than the heap top, remove the top and insert the new element. After processing all elements, the heap contains the K largest. Time O(n log k).

Variations: K most frequent elements (heap of (frequency, element) pairs), K closest points to origin (heap of (distance, point)), K largest in a stream (maintain a min-heap of size K as new elements arrive).

Merge K Sorted Lists

Merge K sorted arrays/lists: insert the first element of each list into a min-heap along with the list index and element index. Pop the min, add it to the result, insert the next element from the same list. Time O(n log k) where n is total elements.

This pattern generalizes to K-way merge of any sorted sources: sorted files, sorted database cursors, sorted log streams. It is the foundation of external sorting algorithms.

Two-Heap Pattern for Median

Maintain a max-heap for the lower half and a min-heap for the upper half. Keep them balanced (size difference at most 1). Median is the top of the larger heap or the average of both tops.

This pattern extends to sliding window median: maintain both heaps and handle removals as the window slides. Removal from a heap is O(log n) with lazy deletion (mark elements as removed, skip them when popped).

Scheduling Problems

Task scheduler: given tasks with cooldown intervals, find the minimum time to complete all tasks. Use a max-heap for task frequencies. After each time unit, decrement and re-add tasks that are ready.

Reorganize string: rearrange characters so no two adjacent characters are the same. Greedy: always pick the most frequent remaining character that is different from the previous. Use a max-heap of (frequency, character) pairs.

Browse Heap and Priority Queue Questions

Real heap problems from Google, Meta, Amazon, and other top companies.

Browse Heap Questions