0
0
DSA Javascriptprogramming~20 mins

Kth Largest Element Using Max Heap in DSA Javascript - Practice Problems & Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Max Heap Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of Kth Largest Element Extraction
What is the output of the following JavaScript code that finds the 3rd largest element using a max heap?
DSA Javascript
class MaxHeap {
  constructor() {
    this.heap = [];
  }
  insert(val) {
    this.heap.push(val);
    this.bubbleUp();
  }
  bubbleUp() {
    let idx = this.heap.length - 1;
    while (idx > 0) {
      let parentIdx = Math.floor((idx - 1) / 2);
      if (this.heap[parentIdx] >= this.heap[idx]) break;
      [this.heap[parentIdx], this.heap[idx]] = [this.heap[idx], this.heap[parentIdx]];
      idx = parentIdx;
    }
  }
  extractMax() {
    if (this.heap.length === 0) return null;
    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 idx = 0;
    const length = this.heap.length;
    const element = this.heap[0];
    while (true) {
      let leftChildIdx = 2 * idx + 1;
      let rightChildIdx = 2 * idx + 2;
      let leftChild, rightChild;
      let swap = null;
      if (leftChildIdx < length) {
        leftChild = this.heap[leftChildIdx];
        if (leftChild > element) swap = leftChildIdx;
      }
      if (rightChildIdx < length) {
        rightChild = this.heap[rightChildIdx];
        if ((swap === null && rightChild > element) || (swap !== null && rightChild > leftChild)) {
          swap = rightChildIdx;
        }
      }
      if (swap === null) break;
      [this.heap[idx], this.heap[swap]] = [this.heap[swap], this.heap[idx]];
      idx = swap;
    }
  }
}

function findKthLargest(nums, k) {
  const maxHeap = new MaxHeap();
  for (const num of nums) {
    maxHeap.insert(num);
  }
  let kthLargest = null;
  for (let i = 0; i < k; i++) {
    kthLargest = maxHeap.extractMax();
  }
  return kthLargest;
}

const nums = [3, 2, 1, 5, 6, 4];
const k = 3;
console.log(findKthLargest(nums, k));
A6
B3
C5
D4
Attempts:
2 left
💡 Hint
Remember the max heap always extracts the largest element first.
🧠 Conceptual
intermediate
1:30remaining
Understanding Max Heap Property
Which statement best describes the max heap property used in finding the kth largest element?
AEvery parent node is smaller than its children.
BEvery parent node is equal to its children.
CEvery parent node is greater than or equal to its children.
DThe heap is sorted in ascending order.
Attempts:
2 left
💡 Hint
Think about what makes the root the largest element.
🔧 Debug
advanced
2:00remaining
Identify the Error in Max Heap Extraction
What error will occur when running this code snippet for extracting max from a max heap?
DSA Javascript
extractMax() {
  if (this.heap.length === 0) return null;
  const max = this.heap[0];
  const end = this.heap.pop();
  this.heap[0] = end;
  this.sinkDown();
  return max;
}
ANo error, works correctly
BRuntime error when heap is empty after pop
CTypeError because sinkDown is not defined
DReferenceError because max is not declared
Attempts:
2 left
💡 Hint
Consider what happens when the heap has only one element.
🚀 Application
advanced
2:00remaining
Resulting Heap After Insertions
After inserting the numbers [10, 4, 15, 20, 0] into an empty max heap, what is the heap array?
A[20, 15, 10, 4, 0]
B[15, 20, 10, 4, 0]
C[20, 10, 15, 4, 0]
D[10, 20, 15, 4, 0]
Attempts:
2 left
💡 Hint
Remember the max heap property after each insertion.
Predict Output
expert
2:30remaining
Output of Kth Largest Element with Duplicate Values
What is the output of the following code that finds the 4th largest element in an array with duplicates using a max heap?
DSA Javascript
class MaxHeap {
  constructor() {
    this.heap = [];
  }
  insert(val) {
    this.heap.push(val);
    this.bubbleUp();
  }
  bubbleUp() {
    let idx = this.heap.length - 1;
    while (idx > 0) {
      let parentIdx = Math.floor((idx - 1) / 2);
      if (this.heap[parentIdx] >= this.heap[idx]) break;
      [this.heap[parentIdx], this.heap[idx]] = [this.heap[idx], this.heap[parentIdx]];
      idx = parentIdx;
    }
  }
  extractMax() {
    if (this.heap.length === 0) return null;
    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 idx = 0;
    const length = this.heap.length;
    const element = this.heap[0];
    while (true) {
      let leftChildIdx = 2 * idx + 1;
      let rightChildIdx = 2 * idx + 2;
      let leftChild, rightChild;
      let swap = null;
      if (leftChildIdx < length) {
        leftChild = this.heap[leftChildIdx];
        if (leftChild > element) swap = leftChildIdx;
      }
      if (rightChildIdx < length) {
        rightChild = this.heap[rightChildIdx];
        if ((swap === null && rightChild > element) || (swap !== null && rightChild > leftChild)) {
          swap = rightChildIdx;
        }
      }
      if (swap === null) break;
      [this.heap[idx], this.heap[swap]] = [this.heap[swap], this.heap[idx]];
      idx = swap;
    }
  }
}

function findKthLargest(nums, k) {
  const maxHeap = new MaxHeap();
  for (const num of nums) {
    maxHeap.insert(num);
  }
  let kthLargest = null;
  for (let i = 0; i < k; i++) {
    kthLargest = maxHeap.extractMax();
  }
  return kthLargest;
}

const nums = [5, 3, 1, 5, 6, 4, 6];
const k = 4;
console.log(findKthLargest(nums, k));
A5
B4
C3
D6
Attempts:
2 left
💡 Hint
Duplicates affect the order but max heap extracts largest each time.