What if you could find the 3rd highest score without sorting the entire list?
Why Kth Largest Element Using Max Heap in DSA Javascript?
Imagine you have a huge pile of exam scores and you want to find the 3rd highest score. You start by sorting all the scores from highest to lowest manually on paper.
This is like trying to find the 3rd largest number by checking each number one by one and comparing it with others.
Sorting all scores manually is slow and tiring, especially if there are hundreds or thousands of scores.
It is easy to make mistakes when comparing many numbers repeatedly.
Also, sorting everything just to find one specific rank wastes a lot of time and effort.
A max heap is like a smart organizer that always keeps the largest score at the top.
Using a max heap, you can quickly remove the largest scores one by one until you reach the kth largest without sorting everything.
This saves time and reduces errors because you only focus on the top scores.
const scores = [50, 20, 80, 90, 30]; scores.sort((a, b) => b - a); const kthLargest = scores[2];
class MaxHeap { constructor() { this.heap = []; } insert(val) { this.heap.push(val); this.bubbleUp(); } bubbleUp() { let index = this.heap.length - 1; const element = this.heap[index]; while (index > 0) { let parentIndex = Math.floor((index - 1) / 2); let parent = this.heap[parentIndex]; if (element <= parent) break; this.heap[parentIndex] = element; this.heap[index] = parent; index = parentIndex; } } extractMax() { const max = this.heap[0]; const end = this.heap.pop(); if (this.heap.length > 0) { this.heap[0] = end; this.sinkDown(); } return max; } sinkDown() { let index = 0; const length = this.heap.length; const element = this.heap[0]; while (true) { let leftChildIndex = 2 * index + 1; let rightChildIndex = 2 * index + 2; let leftChild, rightChild; let swap = null; if (leftChildIndex < length) { leftChild = this.heap[leftChildIndex]; if (leftChild > element) { swap = leftChildIndex; } } if (rightChildIndex < length) { rightChild = this.heap[rightChildIndex]; if ( (swap === null && rightChild > element) || (swap !== null && rightChild > leftChild) ) { swap = rightChildIndex; } } if (swap === null) break; this.heap[index] = this.heap[swap]; this.heap[swap] = element; index = swap; } } } const scores = [50, 20, 80, 90, 30]; const maxHeap = new MaxHeap(); scores.forEach(score => maxHeap.insert(score)); let kthLargest; for (let i = 0; i < 3; i++) { kthLargest = maxHeap.extractMax(); }
This method lets you efficiently find the kth largest element in large data sets without sorting everything.
Finding the 5th highest salary in a company with thousands of employees quickly to decide bonus distribution.
Manual sorting is slow and error-prone for large data.
Max heap keeps the largest element accessible instantly.
Extracting max k times finds the kth largest efficiently.
Practice
kth largest element using a max heap?Solution
Step 1: Understand max heap property
A max heap always keeps the largest element at the root, so extracting the root gives the largest element.Step 2: Extract max
By removing the rootktimes to get thekthlargestktimes, the last extracted element is thekthlargest.Final Answer:
Build max heap and extract maxktimes -> Option AQuick Check:
Max heap extraction =kthlargest element [OK]
k times to find kth largest [OK]- Using min heap instead of max heap
- Sorting and picking wrong index
- Extracting fewer or more than
ktimes
arr in JavaScript using a custom heap class?Solution
Step 1: Recognize typical max heap initialization
Usually, a max heap class accepts an array and has a method likebuildHeap()to create the heap structure.Step 2: Identify correct method call
buildHeap()is the standard method to convert the array into a max heap, so calling it after initialization is correct.Final Answer:
const maxHeap = new MaxHeap(arr); maxHeap.buildHeap(); -> Option DQuick Check:
buildHeap() builds max heap from array [OK]
- Calling insert with whole array instead of single elements
- Using wrong method names like heapify or build
- Not calling any method to build the heap
class MaxHeap {
constructor(arr) {
this.heap = arr;
this.buildHeap();
}
buildHeap() {
for (let i = Math.floor(this.heap.length / 2) - 1; i >= 0; i--) {
this.heapify(i);
}
}
heapify(i) {
let largest = i;
let left = 2 * i + 1;
let right = 2 * i + 2;
if (left < this.heap.length && this.heap[left] > this.heap[largest]) largest = left;
if (right < this.heap.length && this.heap[right] > this.heap[largest]) largest = right;
if (largest !== i) {
[this.heap[i], this.heap[largest]] = [this.heap[largest], this.heap[i]];
this.heapify(largest);
}
}
extractMax() {
if (this.heap.length === 0) return null;
const max = this.heap[0];
this.heap[0] = this.heap.pop();
this.heapify(0);
return max;
}
}
const arr = [3, 2, 1, 5, 6, 4];
const maxHeap = new MaxHeap(arr);
let kthLargest;
for (let i = 0; i < 2; i++) {
kthLargest = maxHeap.extractMax();
}
console.log(kthLargest);Solution
Step 1: Build max heap from array
Array [3,2,1,5,6,4] becomes max heap with root 6 after buildHeap.Step 2: Extract max twice
First extractMax returns 6, second extractMax returns 5, sokthLargestafter loop is 5.Final Answer:
5 -> Option BQuick Check:
2nd largest element = 5 [OK]
- Assuming heap root changes incorrectly after extraction
- Confusing 1st largest with 2nd largest
- Not updating heap after extraction
class MaxHeap {
constructor(arr) {
this.heap = arr;
this.buildHeap();
}
buildHeap() {
for (let i = 0; i < this.heap.length / 2; i++) {
this.heapify(i);
}
}
heapify(i) {
let largest = i;
let left = 2 * i + 1;
let right = 2 * i + 2;
if (left < this.heap.length && this.heap[left] > this.heap[largest]) largest = left;
if (right < this.heap.length && this.heap[right] > this.heap[largest]) largest = right;
if (largest !== i) {
[this.heap[i], this.heap[largest]] = [this.heap[largest], this.heap[i]];
this.heapify(largest);
}
}
extractMax() {
if (this.heap.length === 0) return null;
const max = this.heap[0];
this.heap[0] = this.heap.pop();
this.heapify(0);
return max;
}
}
const arr = [7, 10, 4, 3, 20, 15];
const maxHeap = new MaxHeap(arr);
let kthLargest;
for (let i = 0; i < 3; i++) {
kthLargest = maxHeap.extractMax();
}
console.log(kthLargest);Solution
Step 1: Analyze buildHeap loop direction
Heap building requires heapify calls from last parent to root, so loop must run backwards from middle to 0.Step 2: Identify incorrect loop direction
Current loop runs forwards, which does not correctly heapify the tree, causing incorrect heap structure.Final Answer:
The buildHeap loop should run backwards from middle to 0 -> Option AQuick Check:
buildHeap loop direction = backwards [OK]
- Running buildHeap loop forwards
- Not calling heapify after extractMax
- Swapping with wrong child in heapify
arr = [12, 3, 5, 7, 19, 0, 4], write a JavaScript function using a max heap to find the 4th largest element. What is the output of your function?Solution
Step 1: Build max heap from array
Array becomes max heap with root 19 after heapify.Step 2: Extract max 4 times
Extracted elements in order: 19, 12, 7, 5. The 4th largest is 7.Final Answer:
7 -> Option CQuick Check:
4th largest element = 7 [OK]
k times; last extracted is kth largest [OK]- Extracting fewer times than
k - Confusing 3rd largest with 4th largest
- Not rebuilding heap after extraction
Ready to prove it?
Pass the test and this pattern moves unknown
