Heaps and Priority Queues Questions

Binary heaps and priority queues as data structures: min-heap and max-heap, array layout, sift-up and sift-down, push/pop/peek costs, build-heap (heapify) in O(n), and indexed heaps with decrease-key versus lazy deletion of stale entries. Covers the problems where a heap is the intended tool: top-K and kth largest or smallest selection (including over a one-pass stream and under inserts and deletes), sorting an array whose elements are at most k places out of order with a window heap, the two-heap pattern for running and sliding-window medians (invariants, rebalancing, lazy deletion, testing, and extensions to percentiles, weighted medians, custom orderings and merging structures), k-way merge of sorted lists, arrays, files or streams with bounded memory, scheduling by priority with cancellation and reprioritisation, stable priority queues with tie-breaking, and implementing a heap or priority queue with a language library such as heapq or PriorityQueue (including max-heap behaviour from a min-heap). Boundary: graph shortest-path algorithms, approximate quantile sketches, production streaming-system design, and heapsort and quickselect as sorting and selection algorithms are covered elsewhere.

EasyTechnical
70 practiced

Write a Python function that returns the k largest values from a stream of numbers, given as a generator you can read only once, in descending order. Use O(k) extra memory and O(n log k) time, and do not store the whole stream. Explain why a min-heap of size k is the right tool and what happens to each incoming value.

MediumTechnical
79 practiced

Your running-median structure must handle values that are not plain numbers: objects ordered by a numeric field, strings ordered lexicographically, or timestamps. How do you adapt the heaps, what do you do about ties and duplicates, and how should it behave on NaN or None?

MediumTechnical
91 practiced

During a code review you find a streaming median implementation that balances heaps by comparing sizes, but sometimes the top of lowers is greater than top of highers. What bug could cause this invariant violation? Describe debugging steps you'd take and how to fix it.

HardTechnical
68 practiced

Dijkstra's algorithm needs a priority queue that can lower the priority of an item already inside it. Design such a queue. Compare an indexed heap that supports decrease-key with simply inserting duplicates and skipping stale entries, and explain the memory and time trade-offs.

EasyTechnical
74 practiced

You have two heaps: lowers (max-heap) contains [5, 3, 2], highers (min-heap) contains [6, 8, 9]. Show the steps and resulting heaps after inserting value 7, including any rebalancing required. Explain your decision at each step.

Unlock Full Question Bank

Get access to all 28 Heaps and Priority Queues interview questions and detailed answers.

Sign in to Continue

Join thousands of developers preparing for their dream job.