Heap over row heads
Time O(k log k) Space O(k)Heap of (sum, i, j). Pop k times; after popping (i, j), push (i, j + 1).
nums1 = [1,7,11], nums2 = [2,4,6], k = 3min-heap(list)
out(list)
empty
Step 1/4Rows are nums1, columns nums2, cells are sums. Put the first cell of each row in the heap.
import java.util.*;
class Solution {
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
for (int i = 0; i < Math.min(nums1.length, k); i++) pq.offer(new int[]{nums1[i] + nums2[0], i, 0});
List<List<Integer>> out = new ArrayList<>();
while (!pq.isEmpty() && out.size() < k) {
int[] t = pq.poll();
out.add(List.of(nums1[t[1]], nums2[t[2]]));
if (t[2] + 1 < nums2.length) pq.offer(new int[]{nums1[t[1]] + nums2[t[2] + 1], t[1], t[2] + 1});
}
return out;
}
}Verdict: Never builds all n × m pairs.