MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Heaps & Priority Queues: Min-Heap, Max-Heap, Heapify & Top-K Elements0%
Study Materials
Data Structures & AlgorithmsProgress 0%
1.1Introduction to DSA, Big-O, Big-Omega & Big-Theta Notations1.2Time Complexity Calculation Rules & Common Runtime Patterns1.3Space Complexity, Auxiliary Memory & Stack vs Heap Allocation
7.1Binary Tree Traversals: DFS (Pre, In, Post) & BFS Level-Order7.2Binary Search Trees (BST): Insertion, Deletion, Validation & Inorder Sorting7.3Heaps & Priority Queues: Min-Heap, Max-Heap, Heapify & Top-K Elements
HomeTutorialsData Structures & AlgorithmsHeaps & Priority Queues: Min-Heap, Max-Heap, Heapify & Top-K Elements
Graph Theory: Adjacency Matrix vs List & BFS vs DFS Traversals

Heaps & Priority Queues: Min-Heap, Max-Heap, Heapify & Top-K Elements

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

A Binary Heap is a specialized complete binary tree that satisfies the Heap Property. In a Min-Heap, the key at the root is the absolute minimum among all keys in the tree; in a Max-Heap, the root is the absolute maximum. Heaps power Priority Queues, Heap Sort ($O(n \log n)$), and Dijkstra’s Shortest Path Algorithm.


1. Real-World Analogy: The Hospital Emergency Room (Triage)

Imagine an Emergency Room triage system:

  • Patients do not enter on a First-In-First-Out basis like a grocery store line.
  • A patient arriving with severe cardiac arrest (Highest Priority) is treated immediately, ahead of someone who arrived 2 hours earlier with a minor finger sprain.
  • A Priority Queue ensures that the item with the highest (or lowest) priority is always served in $O(1)$ constant time!

2. Array Representation of a Binary Heap

Because a binary heap is a Complete Binary Tree (every level is completely filled except possibly the last, which is filled from left to right), it can be stored directly inside a contiguous flat array with ZERO pointer overhead:

1Given index i (0-indexed):
2- Parent Node: Math.floor((i - 1) / 2)
3- Left Child Node: 2 * i + 1
4- Right Child Node: 2 * i + 2

3. Core Heap Operations

OperationActionTime Complexity
peek()Inspects the min/max element at the root (arr[0])$O(1)$
insert(val)Adds to the end of array and bubbles up (Sift-Up)$O(\log n)$
extractMin() / pop()Swaps root with last item, pops end, and sinks down (Sift-Down)$O(\log n)$
heapify(arr)Converts an unordered array into a valid heap in-place$O(n)$ Linear Time!

4. Multi-Language Implementations: Top-K Frequent Elements

Find the $K$ most frequent elements in an array using a Min-Heap of size $K$ in $O(n \log k)$ time:

Python 3:

1import heapq
2from collections import Counter
3 
4def top_k_frequent(nums: list[int], k: int) -> list[int]:
5 # 1. Count frequencies in O(n) time
6 count = Counter(nums)
7
8 # 2. Maintain a Min-Heap of size k (stores (frequency, num))
9 # Python's heapq is a Min-Heap by default!
10 min_heap = []
11 for num, freq in count.items():
12 heapq.heappush(min_heap, (freq, num))
13 if len(min_heap) > k:
14 heapq.heappop(min_heap) # Eject lowest frequency element!
15
16 return [num for freq, num in min_heap]

Modern JavaScript / TypeScript (Custom Min-Heap):

1export class MinHeap {
2 private heap: number[] = [];
3 
4 public push(val: number): void {
5 this.heap.push(val);
6 this.siftUp(this.heap.length - 1);
7 }
8 
9 public pop(): number | undefined {
10 if (this.heap.length === 0) return undefined;
11 const min = this.heap[0];
12 const last = this.heap.pop()!;
13 if (this.heap.length > 0) {
14 this.heap[0] = last;
15 this.siftDown(0);
16 }
17 return min;
18 }
19 
20 private siftUp(i: number): void {
21 while (i > 0) {
22 const p = (i - 1) >> 1;
23 if (this.heap[i] < this.heap[p]) {
24 [this.heap[i], this.heap[p]] = [this.heap[p], this.heap[i]];
25 i = p;
26 } else break;
27 }
28 }
29 
30 private siftDown(i: number): void {
31 const n = this.heap.length;
32 while (2 * i + 1 < n) {
33 let smallest = 2 * i + 1; // Left child
34 const right = smallest + 1;
35 if (right < n && this.heap[right] < this.heap[smallest]) {
36 smallest = right;
37 }
38 if (this.heap[i] > this.heap[smallest]) {
39 [this.heap[i], this.heap[smallest]] = [this.heap[smallest], this.heap[i]];
40 i = smallest;
41 } else break;
42 }
43 }
44}

5. Trace Table: Sifting Up [10, 20, 15, 30] after inserting 5

  • Initial Heap: [10, 20, 15, 30]
  • Insert 5 at index 4: [10, 20, 15, 30, 5]
StepIndex iValueParent Index p = (i-1)//2Parent ValueComparisonAction
145120$5 < 20$Swap 5 and 20 → [10, 5, 15, 30, 20]
215010$5 < 10$Swap 5 and 10 → [5, 10, 15, 30, 20]
30 (Root)5--At RootDone!

Result: 5 bubbled up to root in $\log_2 n$ steps!


Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
What is the time complexity to retrieve the minimum element from a Min-Heap without removing it (peek())?
Question 2
For an element at index $i$ in a 0-indexed binary heap array, what formula locates its left child?
Question 3
What is the time complexity of the mathematical heapify operation that transforms an arbitrary array of $n$ elements into a valid heap?
Question 4
When finding the "K-th Largest Element" in an array of $n$ items, what type of heap should you maintain with capacity $K$?
Question 5
What tree structure property guarantees that a Binary Heap can be mapped to a flat array without memory gaps?

Next Lesson

Graph Theory: Adjacency Matrix vs List & BFS vs DFS Traversals

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Binary Search Trees (BST): Insertion, Deletion, Validation & Inorder SortingGraph Theory: Adjacency Matrix vs List & BFS vs DFS Traversals

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Data Structures & Algorithms with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext