Interactive Lab ยท DSA & Algorithms
When an interview asks for the k largest, merge k sorted lists, or the next event in a simulation, the answer is almost always a heap. And a heap is disarmingly simple: it's just an array that obeys one rule, every parent is โค its childrenso the minimum is always sitting at index 0, free to read. No pointers, no balancing act: the tree is implied by the array indices (children(i) = 2i+1, 2i+2). Insert by dropping a value at the end and bubbling it up; remove the min by moving the last value to the root and sifting it down. Step through every compare and swap below.
๐ฌ Watch the 90-second explainer, then build the heap yourself below โ
โถ The playground, 7 pushes build the heap, then 2 pop-mins
The tree is drawn straight from the array underneath, node at index i has children at 2i+1 and 2i+2. The filled node is the value in motion; the ringed node is who it's being compared against. Scrub the step slider to watch a value climb to its level, or the root sink to its place.
Heaps are the priority queues inside OS schedulers (pick the next task), Dijkstra's algorithm (pick the nearest node), event loops and timers (pick the soonest deadline), and top-K queries in every analytics engine. The O(1)-peek/O(log n)-pop contract you just traced is why 'give me the most urgent thing' is cheap at any scale.
The code that's actually running, an array, and two sifts
Drag to the end and watch the two pop-min operations: they hand back 1, then 2the two smallest, in order. Predict: if you kept popping until the heap was empty, in what order would the values come out? (You'd get them fully sortedthat's heapsort, O(n log n), no extra array.) And here's the subtle one: reading the minimum is O(1) because it's always at index 0, so why does a heap not give you the second-smallest in O(1) too? What would you have to do to find it?
The takeaway
i's parent is (iโ1)/2 and its kids are 2i+1, 2i+2. Because it's a complete binary tree, it's always balanced, so its height is exactly โlogโ nโ.