0
0
DSA Typescriptprogramming~20 mins

Kth Largest Element Using Max Heap in DSA Typescript - 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 extracting the 3rd largest element using a max heap
What is the output of the following TypeScript code that finds the 3rd largest element using a max heap?
DSA Typescript
class MaxHeap {
  heap: number[] = [];

  insert(val: number) {
    this.heap.push(val);
    this.bubbleUp();
  }

  bubbleUp() {
    let index = this.heap.length - 1;
    while (index > 0) {
      let parentIndex = Math.floor((index - 1) / 2);
      if (this.heap[parentIndex] >= this.heap[index]) break;
      [this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]];
      index = parentIndex;
    }
  }

  extractMax(): number | undefined {
    if (this.heap.length === 0) return undefined;
    if (this.heap.length === 1) return this.heap.pop();
    const max = this.heap[0];
    this.heap[0] = this.heap.pop()!;
    this.sinkDown(0);
    return max;
  }

  sinkDown(index: number) {
    const length = this.heap.length;
    const element = this.heap[index];
    while (true) {
      let leftChildIdx = 2 * index + 1;
      let rightChildIdx = 2 * index + 2;
      let swapIdx: number | null = null;

      if (leftChildIdx < length) {
        if (this.heap[leftChildIdx] > element) {
          swapIdx = leftChildIdx;
        }
      }
      if (rightChildIdx < length) {
        if (
          (swapIdx === null && this.heap[rightChildIdx] > element) ||
          (swapIdx !== null && this.heap[rightChildIdx] > this.heap[leftChildIdx])
        ) {
          swapIdx = rightChildIdx;
        }
      }
      if (swapIdx === null) break;
      [this.heap[index], this.heap[swapIdx]] = [this.heap[swapIdx], this.heap[index]];
      index = swapIdx;
    }
  }
}

const nums = [7, 10, 4, 3, 20, 15];
const k = 3;
const maxHeap = new MaxHeap();
for (const num of nums) {
  maxHeap.insert(num);
}
let kthLargest: number | undefined;
for (let i = 0; i < k; i++) {
  kthLargest = maxHeap.extractMax();
}
console.log(kthLargest);
A7
B15
C10
D20
Attempts:
2 left
💡 Hint
Remember that the max heap always extracts the largest element first. Extract k times to get the kth largest.
Predict Output
intermediate
2:00remaining
Output after building max heap and extracting max once
What is the state of the heap array after inserting [5, 3, 8, 4] and extracting the max once?
DSA Typescript
class MaxHeap {
  heap: number[] = [];

  insert(val: number) {
    this.heap.push(val);
    this.bubbleUp();
  }

  bubbleUp() {
    let index = this.heap.length - 1;
    while (index > 0) {
      let parentIndex = Math.floor((index - 1) / 2);
      if (this.heap[parentIndex] >= this.heap[index]) break;
      [this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]];
      index = parentIndex;
    }
  }

  extractMax(): number | undefined {
    if (this.heap.length === 0) return undefined;
    if (this.heap.length === 1) return this.heap.pop();
    const max = this.heap[0];
    this.heap[0] = this.heap.pop()!;
    this.sinkDown(0);
    return max;
  }

  sinkDown(index: number) {
    const length = this.heap.length;
    const element = this.heap[index];
    while (true) {
      let leftChildIdx = 2 * index + 1;
      let rightChildIdx = 2 * index + 2;
      let swapIdx: number | null = null;

      if (leftChildIdx < length) {
        if (this.heap[leftChildIdx] > element) {
          swapIdx = leftChildIdx;
        }
      }
      if (rightChildIdx < length) {
        if (
          (swapIdx === null && this.heap[rightChildIdx] > element) ||
          (swapIdx !== null && this.heap[rightChildIdx] > this.heap[leftChildIdx])
        ) {
          swapIdx = rightChildIdx;
        }
      }
      if (swapIdx === null) break;
      [this.heap[index], this.heap[swapIdx]] = [this.heap[swapIdx], this.heap[index]];
      index = swapIdx;
    }
  }
}

const maxHeap = new MaxHeap();
[5, 3, 8, 4].forEach(n => maxHeap.insert(n));
maxHeap.extractMax();
console.log(maxHeap.heap);
A[5, 4, 3]
B[8, 5, 3, 4]
C[5, 4, 3, 8]
D[4, 5, 3]
Attempts:
2 left
💡 Hint
After extracting max, the heap reorders to maintain max heap property.
🔧 Debug
advanced
2:00remaining
Identify the error in max heap sinkDown method
What error will occur when running this sinkDown method in a max heap implementation?
DSA Typescript
sinkDown(index: number) {
  const length = this.heap.length;
  const element = this.heap[index];
  while (true) {
    let leftChildIdx = 2 * index + 1;
    let rightChildIdx = 2 * index + 2;
    let swapIdx: number | null = null;

    if (leftChildIdx < length) {
      if (this.heap[leftChildIdx] < element) {
        swapIdx = leftChildIdx;
      }
    }
    if (rightChildIdx < length) {
      if (
        (swapIdx === null && this.heap[rightChildIdx] < element) ||
        (swapIdx !== null && this.heap[rightChildIdx] < this.heap[leftChildIdx])
      ) {
        swapIdx = rightChildIdx;
      }
    }
    if (swapIdx === null) break;
    [this.heap[index], this.heap[swapIdx]] = [this.heap[swapIdx], this.heap[index]];
    index = swapIdx;
  }
}
AThe sinkDown will incorrectly swap smaller children, breaking max heap property
BThe code will cause an infinite loop because swapIdx is never updated
CThe code will throw a TypeError due to undefined heap elements
DNo error; the sinkDown method works correctly
Attempts:
2 left
💡 Hint
Check the comparison operators used for deciding swaps in a max heap.
🚀 Application
advanced
2:00remaining
Find the 2nd largest element using max heap
Given the array [12, 3, 5, 7, 19], what is the 2nd largest element found by extracting max twice from a max heap?
DSA Typescript
class MaxHeap {
  heap: number[] = [];

  insert(val: number) {
    this.heap.push(val);
    this.bubbleUp();
  }

  bubbleUp() {
    let index = this.heap.length - 1;
    while (index > 0) {
      let parentIndex = Math.floor((index - 1) / 2);
      if (this.heap[parentIndex] >= this.heap[index]) break;
      [this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]];
      index = parentIndex;
    }
  }

  extractMax(): number | undefined {
    if (this.heap.length === 0) return undefined;
    if (this.heap.length === 1) return this.heap.pop();
    const max = this.heap[0];
    this.heap[0] = this.heap.pop()!;
    this.sinkDown(0);
    return max;
  }

  sinkDown(index: number) {
    const length = this.heap.length;
    const element = this.heap[index];
    while (true) {
      let leftChildIdx = 2 * index + 1;
      let rightChildIdx = 2 * index + 2;
      let swapIdx: number | null = null;

      if (leftChildIdx < length) {
        if (this.heap[leftChildIdx] > element) {
          swapIdx = leftChildIdx;
        }
      }
      if (rightChildIdx < length) {
        if (
          (swapIdx === null && this.heap[rightChildIdx] > element) ||
          (swapIdx !== null && this.heap[rightChildIdx] > this.heap[leftChildIdx])
        ) {
          swapIdx = rightChildIdx;
        }
      }
      if (swapIdx === null) break;
      [this.heap[index], this.heap[swapIdx]] = [this.heap[swapIdx], this.heap[index]];
      index = swapIdx;
    }
  }
}

const nums = [12, 3, 5, 7, 19];
const maxHeap = new MaxHeap();
for (const num of nums) {
  maxHeap.insert(num);
}
maxHeap.extractMax();
const secondLargest = maxHeap.extractMax();
console.log(secondLargest);
A19
B12
C7
D5
Attempts:
2 left
💡 Hint
Extract max twice; the first extraction removes the largest, the second is the 2nd largest.
🧠 Conceptual
expert
2:00remaining
Time complexity of finding kth largest element using max heap
What is the time complexity of finding the kth largest element in an unsorted array of size n by building a max heap and extracting max k times?
AO(nk)
BO(n log n + k)
CO(k log n)
DO(n + k log n)
Attempts:
2 left
💡 Hint
Building a max heap from n elements takes O(n). Each extraction takes O(log n).