Skip to content
DSA Patterns
Menu
Language
Heap & Top KLC #3735 of 6← PreviousNext →

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

Find K Pairs with Smallest Sums

Problem (restated)

Two sorted ascending arrays. Return k pairs (u,v) with u from nums1, v from nums2, with the smallest sums.

Intuition

Start with (nums1[i], nums2[0]) for i < k. Pop smallest sum; push next j+1 for same i.

Approaches

Min-heap over first column

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

Idea. Avoid full n×m matrix. Heap expands along nums2 for the best rows only.

Walkthrough. [1,7,11]×[2,4,6], k=3 → [1,2],[1,4],[1,6].

Trade-offs. Sorted arrays are essential; without order fall back to full sort of pairs.

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;
  }
}
/** 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 function kSmallestPairs(nums1: number[], nums2: number[], k: number): number[][] {
  const res: number[][] = [];
  if (!nums1.length || !nums2.length || k <= 0) return res;
  // Real binary min-heap of [sum, i, j].
  const heap = new Heap<[number, number, number]>((a, b) => a[0]! < b[0]!);
  const push = (i: number, j: number) => {
    heap.push([nums1[i]! + nums2[j]!, i, j]);
  };
  const n1 = Math.min(nums1.length, k);
  for (let i = 0; i < n1; i++) push(i, 0);
  while (k-- > 0 && heap.size) {
    const [, i, j] = heap.pop();
    res.push([nums1[i]!, nums2[j]!]);
    if (j + 1 < nums2.length) push(i, j + 1);
  }
  return res;
}
export function kSmallestPairs(nums1: number[], nums2: number[], k: number): number[][] {
  const res: number[][] = [];
  if (!nums1.length || !nums2.length || k <= 0) return res;
  // Real binary min-heap of [sum, i, j].
  const heap = new Heap<[number, number, number]>((a, b) => a[0]! < b[0]!);
  const push = (i: number, j: number) => {
    heap.push([nums1[i]! + nums2[j]!, i, j]);
  };
  const n1 = Math.min(nums1.length, k);
  for (let i = 0; i < n1; i++) push(i, 0);
  while (k-- > 0 && heap.size) {
    const [, i, j] = heap.pop();
    res.push([nums1[i]!, nums2[j]!]);
    if (j + 1 < nums2.length) push(i, j + 1);
  }
  return res;
}

Template connection

K-way heap seeded with the first column: (nums1[i], nums2[0]) for i < min(k, n). Pop the smallest sum and push the next index in that same nums2 row. The n×m matrix is never built.

Reflection

  • Seed the heap with nums1[i] + nums2[0] for each row. After a pop, push the next column j + 1 in that row.
  • The same pair must not be pushed twice. A visited set does it. So does the shape where only j moves.
  • If k is larger than the number of pairs, return all of them. One empty array: the answer is empty.
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

k smallest pairs from [1, 7, 11] × [2, 4, 6], k=3. Heap starts at every (i, 0) for i < k.

1
0
7
1
11
2
stack
∅
mapnums2→2, 4, 6

k = 3

Key:CurrentActive rangeMatchSettledEliminated