Skip to the page

Recursion, trees and heaps · mid

Heaps and priority queues in JavaScript

JavaScript has no built-in heap, so you write a small binary heap in an array (the parent of i is (i − 1) >> 1) with a comparator. It gives O(log n) push and pop, and you use it for top-k, merging sorted lists and scheduling by priority.

The notes

What you must know

  • Array layout: children of i are 2i + 1 and 2i + 2; parent is (i − 1) >> 1.
  • push: append, then sift up while smaller than the parent. pop: take a[0], move the last item to the root, sift down to the smaller child.
  • A comparator (a, b) => a - b gives a min-heap; (a, b) => b - a a max-heap; compare tuples for ties (priority, then insertion order) to keep FIFO.
  • Top k largest: keep a MIN-heap of size k (O(n log k)); the root is the k-th largest.
  • Merge k sorted lists: heap of the current head of each list, O(N log k).
  • If n is small or the interviewer allows it, sort is fine — say the trade-off. Quickselect gives O(n) average for k-th largest.
  • Frontend links: task scheduler with priorities, event loop-like simulations, calendar layout (free column by earliest end).

The red pen

Common traps: mistake → fix

  • Mistake: Sorting after every insert is a priority queue

    Fix: that is O(n log n) per insert.

  • Mistake: Top-k largest needs a max-heap of all items

    Fix: a min-heap of size k is cheaper in memory and time.

  • Mistake: Heap order means the array is sorted

    Fix: only the parent-child relation holds.

Easy to hard

Questions interviewers ask, easy to hard

  1. JavaScript has no priority queue. Implement one.
  2. Find the k-th largest element. What is the complexity?
  3. Top k frequent elements.
  4. Merge k sorted arrays.

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview