ZZomato·BehavioralL3DSA Round

Min-Heap Internal Structure

viaGlassdoor

Q: You said you'd use a min-heap here - how is a min-heap implemented internally? A: A min-heap is typically implemented as a complete binary tree stored in a flat array, where for a node at index i, its children are at 2i+1 and 2i+2, and its parent is at (i-1)/2. The heap property ensures every parent is <= its children, so the minimum is always at index 0. insert appends the new element at the end and 'bubbles up' (sift-up) by swapping with its parent while smaller than the parent - O(log n). extractMin swaps the root with the last element, removes the last element, then 'bubbles down' (sift-down/heapify) the new root by repeatedly swapping with its smaller child - O(log n). Peeking at the min is O(1).

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account