Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Min Heap Implementation in TypeScript

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Min Heap runs in O(log n) time and O(n) space, in TypeScript as in every other language.
  • ✓The same absence as JavaScript, no heap in the standard library, but generics let one MinHeap<T> serve every element type with a typed (a: T, b: T) => number comparator, so the comparator can no longer be forgotten or mistyped at the call site.
  • ✓Require the comparator as a constructor argument rather than defaulting it. A default comparator only type-checks for number, and providing one invites the silent lexicographic bug from the JavaScript side; making it mandatory pushes the ordering decision to the place that knows the element type.
  • ✓The TypeScript trap: Turning on noUncheckedIndexedAccess, which you should, types every items[i] as T | undefined, and the sift loops become a wall of non-null assertions.
  • ✓Identical to JavaScript at runtime; types are erased. The one thing generics change is that a heap of a union type or an interface holds boxed object references rather than packed numbers, so if the elements are conceptually numeric it is worth keeping them numeric and storing payloads in a parallel array.

What Min Heap actually is

A min-heap is a complete binary tree kept in a flat array where every parent is no larger than its children, which makes the smallest element always sit at index zero. Insertion pushes to the end and sifts up; extraction swaps the last element into the root and sifts down. Both are O(log n) because the tree height is log n, and the flat-array layout means the children of index i live at 2i+1 and 2i+2 with no pointers at all. It is the data structure underneath every priority queue, Dijkstra, A*, task scheduler and top-k query. The languages below split sharply into three groups: those whose standard library hands you a min-heap, those that hand you a MAX-heap and make you invert it, and those that hand you nothing.

Min Heap in TypeScript: what you actually reach for

The same absence as JavaScript, no heap in the standard library, but generics let one MinHeap<T> serve every element type with a typed (a: T, b: T) => number comparator, so the comparator can no longer be forgotten or mistyped at the call site.

TypeScript implementation

Require the comparator as a constructor argument rather than defaulting it. A default comparator only type-checks for number, and providing one invites the silent lexicographic bug from the JavaScript side; making it mandatory pushes the ordering decision to the place that knows the element type.
typescript
export class MinHeap<T> {
  private readonly items: T[] = [];

  // Mandatory, not defaulted: a default only works for number and invites
  // the silent lexicographic-sort bug.
  constructor(private readonly compare: (a: T, b: T) => number) {}

  get size(): number { return this.items.length; }

  push(value: T): void {
    this.items.push(value);
    let i = this.items.length - 1;
    while (i > 0) {
      const parent = (i - 1) >> 1;
      // Read into locals: narrows T | undefined under noUncheckedIndexedAccess
      const a = this.items[i] as T;
      const b = this.items[parent] as T;
      if (this.compare(a, b) >= 0) break;
      this.items[i] = b;
      this.items[parent] = a;
      i = parent;
    }
  }

  pop(): T | undefined {
    if (this.items.length === 0) return undefined;
    const top = this.items[0] as T;
    const last = this.items.pop() as T;
    if (this.items.length > 0) {
      this.items[0] = last;
      this.siftDown(0);
    }
    return top;
  }

  private siftDown(start: number): void {
    let i = start;
    for (;;) {
      const l = 2 * i + 1;
      const r = l + 1;
      let smallest = i;
      if (l < this.items.length &&
          this.compare(this.items[l] as T, this.items[smallest] as T) < 0) smallest = l;
      if (r < this.items.length &&
          this.compare(this.items[r] as T, this.items[smallest] as T) < 0) smallest = r;
      if (smallest === i) return;
      const a = this.items[i] as T;
      this.items[i] = this.items[smallest] as T;
      this.items[smallest] = a;
      i = smallest;
    }
  }
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The TypeScript-specific trap

Turning on noUncheckedIndexedAccess, which you should, types every items[i] as T | undefined, and the sift loops become a wall of non-null assertions. The clean fix is to read each index into a local const once and compare the locals, which satisfies the compiler through narrowing instead of suppressing it, and happens to read better too.

Performance in TypeScript, beyond the O(log n)

Identical to JavaScript at runtime; types are erased. The one thing generics change is that a heap of a union type or an interface holds boxed object references rather than packed numbers, so if the elements are conceptually numeric it is worth keeping them numeric and storing payloads in a parallel array. The asymptotic cost is the same in every language, O(log n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Min Heap between languages.

Real-World Applications

Min Heap applies wherever its problem shape appears in your own code. In TypeScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Min Heap helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Min Heap appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Min Heap over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Min Heap to build pattern recognition. In TypeScript, demonstrate proficiency with generics and type guards to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic TypeScript code that is both correct and maintainable.

Frequently Asked Questions

Which TypeScript type or library should I use for Min Heap?

The same absence as JavaScript, no heap in the standard library, but generics let one MinHeap<T> serve every element type with a typed (a: T, b: T) => number comparator, so the comparator can no longer be forgotten or mistyped at the call site.

What is the most common TypeScript mistake when implementing Min Heap?

Turning on noUncheckedIndexedAccess, which you should, types every items[i] as T | undefined, and the sift loops become a wall of non-null assertions. The clean fix is to read each index into a local const once and compare the locals, which satisfies the compiler through narrowing instead of suppressing it, and happens to read better too.

How does Min Heap actually perform in TypeScript?

Identical to JavaScript at runtime; types are erased. The one thing generics change is that a heap of a union type or an interface holds boxed object references rather than packed numbers, so if the elements are conceptually numeric it is worth keeping them numeric and storing payloads in a parallel array. Time complexity is O(log n) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

If you are a student, see what Replit offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.