This site uses one functional cookie to keep feature rollouts consistent for you. Nothing is set until you choose. See the privacy notice.
Phase 2: Structures
Always know the smallest (or biggest) thing, cheaply, while things keep changing.
Builds on Hash Maps & Sets.
The question to ask
Do I keep needing the current smallest or largest item while items are added and removed?
A heap gives you the minimum in O(1) and lets you add or remove in O(log n). Reach for one when you repeatedly need the current best: the k largest of a stream, the next meeting to end, the closest unvisited node, the smallest head among k sorted lists. The counter-intuitive move is keeping a min-heap of size k to find the k largest: the root is the weakest of the current top k, so anything smaller than it is out.
Time O(n log k) for top k · Space O(k)
Write it from memory first, in an editor or on paper, then check. Recalling it is what makes it stick; reading it again mostly doesn't.
The heap holds at most one node per list: the current head. Pop the smallest, append it, push its successor. O(N log k) for N nodes total.
function mergeKLists(lists: (ListNode | null)[]): ListNode | null {
const heap = new MinHeap<ListNode>((a, b) => a.val - b.val);
for (const head of lists) if (head) heap.push(head);
const dummy = new ListNode();
let tail = dummy;
while (heap.size > 0) {
const node = heap.pop() as ListNode;
tail.next = node;
tail = node;
if (node.next) heap.push(node.next);
}
return dummy.next;
}low is a max-heap of the smaller half, high a min-heap of the larger half. Add to low, move low's max to high, and rebalance so low is never smaller. The median is low's top or the average of both tops.
class MedianFinder {
private low = new MinHeap<number>((a, b) => b - a);
private high = new MinHeap<number>((a, b) => a - b);
addNum(num: number): void {
this.low.push(num);
this.high.push(this.low.pop() as number);
if (this.high.size > this.low.size) this.low.push(this.high.pop() as number);
}
findMedian(): number {
if (this.low.size > this.high.size) return this.low.peek() as number;
return ((this.low.peek() as number) + (this.high.peek() as number)) / 2;
}
}Easy to hard. Read the prompt and name the signal before opening the tell. After each attempt, rate it: Again brings it back tomorrow, Hard holds the interval, Good and Easy push it further out.
Repeatedly smash the two heaviest stones together; equal stones vanish, otherwise the difference remains. Return the weight of the last stone, or 0.
"Two heaviest" again and again while new stones appear: a max-heap.
Not attempted yet
Design a class that receives numbers from a data stream and returns the kth largest element after each one.
"Kth largest" of a "data stream": keep a min-heap of size k; its root is always the answer.
Not attempted yet
Return the kth largest element in an unsorted array. Can you solve it without sorting?
"Kth largest" without sorting: a size-k min-heap, O(n log k). Quickselect is the O(n) average answer to mention.
Not attempted yet
Given points on a plane, return the k closest points to the origin.
"K closest": a max-heap of size k by squared distance (no square root needed), evicting the farthest.
Not attempted yet
Each task takes one unit of time and identical tasks need n units of cooling between them. Return the minimum time to finish all tasks.
Most frequent task first, held back while cooling: a max-heap plus a cooldown queue. The counting formula is the faster answer to know.
Not attempted yet
Rearrange the characters so that two adjacent characters are not the same, or return an empty string if impossible.
"Adjacent characters are not the same": always place the most frequent remaining letter that isn't the previous one. Max-heap by count.
Not attempted yet
Given two sorted arrays, return the k pairs with the smallest sums, one element from each array.
"K pairs with the smallest" sums: seed a min-heap with (i, 0) pairs and expand each popped pair's neighbour lazily.
Not attempted yet
Merge k sorted linked lists into one sorted linked list.
"Merge k sorted": a heap of the current heads always yields the next smallest. O(N log k).
Not attempted yet
Design a structure that adds numbers from a data stream and returns the median of everything added so far.
"Median" of a "data stream": two heaps, max-heap for the low half and min-heap for the high half, kept balanced.
Not attempted yet
You have initial capital and can finish at most k projects, each with a capital requirement and a profit. Maximise your final capital.
Projects unlock as "capital" grows: sort by requirement, push affordable ones into a max-heap by profit, take the best each round.
Not attempted yet