What is a heap?
Why Interviewers Ask This
Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid Data Structures & Algorithms basics — a prerequisite for any developer role.
Answer
A heap is a complete binary tree satisfying the heap property. Two types: (1) Max-heap: every parent is ≥ its children — root is the maximum element; (2) Min-heap: every parent is ≤ its children — root is the minimum element. Implementation: typically stored in an array (no explicit tree structure needed for a complete binary tree). For node at index i: left child = 2i+1, right child = 2i+2, parent = (i-1)/2. Operations: Insert: add at end, then sift up (bubble up) to restore heap property: O(log n); Extract-max/min: remove root, move last element to root, sift down: O(log n); Peek: O(1) — root is always max/min; Build heap from array: O(n) — use sift-down starting from last non-leaf. Applications: Priority queue ADT; Heap sort — build max-heap, repeatedly extract max: O(n log n), O(1) space; Top K elements problem; Merge K sorted lists; Dijkstra's/Prim's algorithms. Python: heapq (min-heap). Java: PriorityQueue. C++: priority_queue.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Data Structures & Algorithms codebase.