Skip to content
DSA Patterns
Menu
Language
Heap & Top KLC #231 of 6Next →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Merge k Sorted Lists

Problem (restated)

Merge k sorted linked lists into one sorted list.

Intuition

Always take the smallest current head among k lists via a min-heap.

Approaches

Min-heap of heads

Unverified
Time O(N log k)Space O(k)

Idea. Heap of (val, list index / node); pop min, push its next.

Walkthrough. [[1,4,5],[1,3,4],[2,6]] → 1→1→2→3→4→4→5→6.

Trade-offs. Heap vs divide-and-conquer merge.

Solution
Show helper code
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
  private a: T[] = [];
  private less: (x: T, y: T) => boolean;
  constructor(less: (x: T, y: T) => boolean) {
    this.less = less;
  }
  get size(): number {
    return this.a.length;
  }
  peek(): T {
    return this.a[0]!;
  }
  push(x: T): void {
    const a = this.a;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!this.less(a[i]!, a[p]!)) break;
      [a[i], a[p]] = [a[p]!, a[i]!];
      i = p;
    }
  }
  pop(): T {
    const a = this.a;
    const top = a[0]!;
    const last = a.pop()!;
    if (a.length) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let s = i;
        if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
        if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
        if (s === i) break;
        [a[i], a[s]] = [a[s]!, a[i]!];
        i = s;
      }
    }
    return top;
  }
}

export class ListNode {
  val: number;
  next: ListNode | null;
  constructor(val = 0, next: ListNode | null = null) {
    this.val = val;
    this.next = next;
  }
}
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
  private a: T[] = [];
  private less: (x: T, y: T) => boolean;
  constructor(less: (x: T, y: T) => boolean) {
    this.less = less;
  }
  get size(): number {
    return this.a.length;
  }
  peek(): T {
    return this.a[0]!;
  }
  push(x: T): void {
    const a = this.a;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!this.less(a[i]!, a[p]!)) break;
      [a[i], a[p]] = [a[p]!, a[i]!];
      i = p;
    }
  }
  pop(): T {
    const a = this.a;
    const top = a[0]!;
    const last = a.pop()!;
    if (a.length) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let s = i;
        if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
        if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
        if (s === i) break;
        [a[i], a[s]] = [a[s]!, a[i]!];
        i = s;
      }
    }
    return top;
  }
}

export class ListNode {
  val: number;
  next: ListNode | null;
  constructor(val = 0, next: ListNode | null = null) {
    this.val = val;
    this.next = next;
  }
}
export function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
  // Real binary min-heap ordered by node value.
  const heap = new Heap<ListNode>((a, b) => a.val < b.val);
  for (const h of lists) if (h) heap.push(h);
  const dummy = new ListNode(0);
  let cur = dummy;
  while (heap.size) {
    const n = heap.pop();
    cur.next = n;
    cur = n;
    if (n.next) heap.push(n.next);
  }
  return dummy.next;
}
export function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
  // Real binary min-heap ordered by node value.
  const heap = new Heap<ListNode>((a, b) => a.val < b.val);
  for (const h of lists) if (h) heap.push(h);
  const dummy = new ListNode(0);
  let cur = dummy;
  while (heap.size) {
    const n = heap.pop();
    cur.next = n;
    cur = n;
    if (n.next) heap.push(n.next);
  }
  return dummy.next;
}

Pairwise merge

Unverified
Time O(Nk)Space O(1) extra

Idea. Fold the lists left to right with two-list merge. The heap version is the k-way form; this one is the merge primitive.

Trade-offs. Each fold copies a longer prefix, so the total is O(Nk). Pairing the lists in a tree is O(N log k). The heap is the usual interview choice.

Solution
Show helper code
export class ListNode {
  val: number;
  next: ListNode | null;
  constructor(val = 0, next: ListNode | null = null) {
    this.val = val;
    this.next = next;
  }
}
export class ListNode {
  val: number;
  next: ListNode | null;
  constructor(val = 0, next: ListNode | null = null) {
    this.val = val;
    this.next = next;
  }
}
function mergeTwo(a: ListNode | null, b: ListNode | null): ListNode | null {
  const dummy = new ListNode(0);
  let cur = dummy;
  while (a && b) {
    if (a.val <= b.val) {
      cur.next = a;
      a = a.next;
    } else {
      cur.next = b;
      b = b.next;
    }
    cur = cur.next;
  }
  cur.next = a ?? b;
  return dummy.next;
}

/** Merge lists left-to-right with two-list merge. */
export function mergeKListsPairwise(lists: Array<ListNode | null>): ListNode | null {
  let acc: ListNode | null = null;
  for (const h of lists) acc = mergeTwo(acc, h);
  return acc;
}
function mergeTwo(a: ListNode | null, b: ListNode | null): ListNode | null {
  const dummy = new ListNode(0);
  let cur = dummy;
  while (a && b) {
    if (a.val <= b.val) {
      cur.next = a;
      a = a.next;
    } else {
      cur.next = b;
      b = b.next;
    }
    cur = cur.next;
  }
  cur.next = a ?? b;
  return dummy.next;
}

/** Merge lists left-to-right with two-list merge. */
export function mergeKListsPairwise(lists: Array<ListNode | null>): ListNode | null {
  let acc: ListNode | null = null;
  for (const h of lists) acc = mergeTwo(acc, h);
  return acc;
}

Template connection

K-way merge: a min-heap of each list’s current head. Pop the smallest, append it, and push that node’s next. The heap stays at most k long. Pairwise merge is the two-list merge, repeated across the lists.

Reflection

  • The min-heap holds each list’s current head. You push the popped node’s next. Empty lists never enter.
  • On a tie the comparator has to decide from the value alone. Comparing node with node throws.
  • Every list empty: null. One list: that list. k = 1: that list’s existing order.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Merge k sorted lists. Min-heap of the current heads: 1, 1, 2.

1
4
5
1
3
4
2
6
stack
2C
1B
1A

heap = [1, 1, 2]

Key:CurrentActive rangeMatchSettled