Core Module
12 min forge

Heap Basics

Master the Priority Queue engine. Learn how heaps maintain the 'Max' or 'Min' element at the top in O(1) time.

πŸ”οΈ Binary Heap: Priority Mastery

A Binary Heap is a complete binary tree where every node follows the Heap Property:

  • Max-Heap: Parent $\ge$ Children (Root is the Maximum).
  • Min-Heap: Parent $\le$ Children (Root is the Minimum).

πŸ’‘ The Logic (ELI5)

Think of an Emergency Room (ER):

  1. Patients don't wait in the order they arrive (Queue).
  2. They wait based on Severity (Priority).
  3. The most critical patient is always moved to the "Root" (the doctor's office).
  4. When that patient is treated, the staff quickly re-evaluates everyone to find the next most critical patient to move to the top.

πŸ” The Deep Dive

Array Representation (Pro Feature)

Heaps are almost never stored as a "Tree" with pointers. Because it's a Complete Binary Tree, we store it in a simple Array! For a node at index i:

  • Left Child: 2 * i + 1
  • Right Child: 2 * i + 2
  • Parent: Math.floor((i - 1) / 2)

Complexity Analysis

  • Peek Max/Min: $O(1)$
  • Insert: $O(\log n)$ (Add to end, then "Bubble Up")
  • Remove Root: $O(\log n)$ (Move last element to root, then "Bubble Down")
  • Build Heap: $O(n)$

πŸ› οΈ Code Forge: Min-Heap Logic

javascript Standard
class MinHeap { constructor() { this.heap = []; } insert(val) { this.heap.push(val); this.bubbleUp(this.heap.length - 1); } bubbleUp(index) { while (index > 0) { let parent = Math.floor((index - 1) / 2); if (this.heap[parent] <= this.heap[index]) break; // Swap [this.heap[parent], this.heap[index]] = [this.heap[index], this.heap[parent]]; index = parent; } } pop() { if (this.heap.length === 0) return null; if (this.heap.length === 1) return this.heap.pop(); const min = this.heap[0]; this.heap[0] = this.heap.pop(); this.bubbleDown(0); return min; } }

🎯 Interview Pulse

Top Use Cases

  • Priority Queues: Task scheduling, Dijkstra's Algorithm.
  • Top K Elements: Finding the 5 largest items in a stream of millions.
  • Median Flow: Using a Max-Heap and a Min-Heap together to find the median of a moving stream of numbers.

Common Questions

  • How is a Heap different from a Binary Search Tree? (Answer: Heap doesn't care about left vs right order, only Parent-Child order).
  • Why do we use an array to store a heap?
  • Implement extractMax and heapify. πŸ’Ž