2Brute2Best
🔥0
02

Kth smallest across lists (K-way Merge Sub-pattern)

Don't build the whole merge: pop from the merged stream k times. Each list can be a row of a matrix, a numerator's fractions, or a row of pair sums.

Signals in the problem statement
  • ›

    "kth smallest element in a sorted matrix"

  • ›

    "k pairs with the smallest sums" from two sorted arrays

  • ›

    "kth smallest fraction / sum"

What makes it different

Sorted Matrix: each row is a list; push the right neighbour. K Pairs: list i is nums1[i] + nums2[0], nums1[i] + nums2[1], …; seed with j = 0 for every i and only move j, so no pair is reached twice. Prime Fraction: list i is arr[i] / arr[n−1] < arr[i] / arr[n−2] < …; compare fractions by cross-multiplying, never with doubles. Kth Smallest Sum of a Matrix: merge the rows two at a time with the K Pairs routine, keeping only the k smallest sums each time.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Kth Smallest Element in a Sorted Matrix
    Basic Anchor·LeetCode #378
    Medium
  2. 2
    Find K Pairs with Smallest Sums
    Basic Reinforcement·LeetCode #373
    Medium
  3. 3
    K-th Smallest Prime Fraction
    Slight Variation·LeetCode #786
    Medium
  4. 4Hard

Template

kth-across-template.cpp
// Kth smallest in a matrix whose rows (and columns) are sorted: pop k times.
int kthSmallest(vector<vector<int>>& matrix, int k) {
    int n = matrix.size();
    priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<>> pq;  // (value, row, col)
    for (int r = 0; r < min(n, k); r++) pq.push({matrix[r][0], r, 0});  // rows past k can't matter
    for (int pops = 1; pops < k; pops++) {                  // throw away the k-1 smallest
        auto [v, r, c] = pq.top(); pq.pop();
        if (c + 1 < (int)matrix[r].size()) pq.push({matrix[r][c + 1], r, c + 1});
    }
    return get<0>(pq.top());                                // the kth pop
}
Remember this · K-way Merge
Trigger
K sorted lists/arrays, kth smallest across sorted rows, smallest range covering all lists.
Think
The next smallest item overall must be the front of some list — which one?
Key question
What do I push back into the heap after popping?