QA
Beginner LevelData Structures & Algorithms

What is a Heap (Min-Heap / Max-Heap) and how is it used as a Priority Queue?

ā“ Interview Prompt: Explain Heap structure, heap property, O(log N) push/pop, O(1) peek, and the K largest / K smallest elements problem.

A Heap is a complete binary tree stored as an array satisfying the heap property:

•
Max-Heap: Parent ≄ children (root = maximum element).
•
Min-Heap: Parent ≤ children (root = minimum element).

Key Operations:

| Operation | Time |

|---|---|

| Insert (sift-up) | $O(\log N)$ |

| Remove root (sift-down) | $O(\log N)$ |

| Peek (root) | $O(1)$ |

| Build heap (heapify) | $O(N)$ |

Parent/Child Index in Array (0-indexed):

•
Parent of $i$: Math.floor((i - 1) / 2)
•
Left child: 2i + 1, Right child: 2i + 2

Code Implementation Example

typescript
// Find K largest elements using a Min-Heap of size K — O(N log K)
// (In interviews, simulate with a sorted structure or JS arr.sort)

function kLargest(nums: number[], k: number): number[] {
  // Use a Min-Heap of size K: maintain K largest seen
  const heap: number[] = [];
  for (const n of nums) {
    heap.push(n);
    heap.sort((a, b) => a - b); // simulated min-heap
    if (heap.length > k) heap.shift(); // pop minimum
  }
  return heap; // remaining K elements are largest
}

// Proper heap gives O(N log K); this simulation is O(N K log K) — for illustration
console.log(kLargest([3, 1, 5, 12, 2, 11], 3)); // [5, 12, 11]
šŸ’”K Largest Elements using a Min-Heap of size K.
šŸŽÆ Interview Key Takeaway

Use a Min-Heap of size K for K-largest problems. Heap sort achieves O(N log N) with O(1) space — an in-place advantage over Merge Sort.

#DSA#Heap#Priority Queue#Min-Heap#Beginner
Back to all Data Structures & Algorithms Questions→

More Data Structures & Algorithms Interview Questions

Beginner LevelData Structures & Algorithms

What is the difference between an Array and a Linked List?

Beginner LevelData Structures & Algorithms

What is Big-O Notation and why is it important?

Beginner LevelData Structures & Algorithms

What are Stack and Queue data structures and where are they used?