Intermediate·Concept·2 min read

Heap and priority queue in JavaScript

Practice this question

Custom min-heap

JavaScript
class MinHeap {
  constructor() {
    this.heap = [];
  }

  push(val) {
    this.heap.push(val);
    this.bubbleUp(this.heap.length - 1);
  }

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

Problems to practice

  • Kth largest element
  • Top K frequent elements
  • Merge K sorted lists

Adapted from 16_DSA_JAVASCRIPT.md · “8. Heap and priority queue in JavaScript”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.