Find K Pairs with Smallest Sums (LeetCode 373): Solution and Explanation

Medium
Array
Heap

You have two arrays sorted in ascending order and an integer k. Each pair takes one element from each array, and you must return the k pairs whose sums are smallest.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force builds all m × n pairs, sorts them by sum and takes the first k. With arrays of up to 100,000 elements that is billions of pairs, so it is hopeless, even though k itself is modest. The goal is to generate pairs in increasing order of sum and stop after k of them.

Picture the pairs as an m × n grid where cell (i, j) holds nums1[i] + nums2[j]. Because both arrays are sorted, sums grow as you move right or down. The smallest sum is always at (0, 0), and once you have taken cell (i, j), the only new cells that could be next are its right neighbor (i, j + 1) and its lower neighbor (i + 1, j). Every other candidate is reachable from some cell already in your frontier.

This is the same idea as merging sorted lists. Keep a min-heap of frontier cells keyed by sum. Pop the smallest, record its pair, and push its two neighbors. Since a cell can be reached from both its upper and left neighbor, a visited set makes sure each cell is pushed only once. After k pops you are done, and you never looked at most of the grid.

Approach: Min-heap over the sum grid

  1. Return an empty list if either array is empty.
  2. Push (nums1[0] + nums2[0], 0, 0) onto the heap and mark (0, 0) as visited.
  3. While the heap is not empty and fewer than k pairs are collected, pop the smallest (sum, i, j).
  4. Append [nums1[i], nums2[j]] to the result.
  5. If (i + 1, j) is in range and unvisited, push it with its sum and mark it visited.
  6. Do the same for (i, j + 1), then loop until k pairs are found or the heap is empty.

Step-by-step example

nums1 = [1, 7, 11], nums2 = [2, 4, 6], k = 3
  1. The heap starts with (3, 0, 0). Popping it adds [1, 2] and pushes (9, 1, 0) for 7 + 2 and (5, 0, 1) for 1 + 4.
  2. The smallest entry is now (5, 0, 1). Popping it adds [1, 4] and pushes (11, 1, 1) for 7 + 4 and (7, 0, 2) for 1 + 6.
  3. The heap holds sums 7, 9 and 11. Popping (7, 0, 2) adds [1, 6].
  4. The result has 3 pairs, so the loop stops and returns [[1, 2], [1, 4], [1, 6]].

Code: Python, Java, C++

1class Solution:
2    def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
3        if not nums1 or not nums2:
4            return []
5        import heapq
6        result = []
7        heap = [(nums1[0] + nums2[0], 0, 0)]
8        visited = {(0, 0)}
9        while heap and len(result) < k:
10            _, i, j = heapq.heappop(heap)
11            result.append([nums1[i], nums2[j]])
12            if i + 1 < len(nums1) and (i + 1, j) not in visited:
13                heapq.heappush(heap, (nums1[i + 1] + nums2[j], i + 1, j))
14                visited.add((i + 1, j))
15            if j + 1 < len(nums2) and (i, j + 1) not in visited:
16                heapq.heappush(heap, (nums1[i] + nums2[j + 1], i, j + 1))
17                visited.add((i, j + 1))
18        return result

Time and space complexity

Time

O(k log k)

There are k pops and at most 2k pushes, and the heap never holds more than about 2k entries, so each operation costs O(log k).

Space

O(k)

The heap and the visited set each hold at most O(k) cells, plus the output of k pairs.

Other approaches

Seed the heap with the first column (time O(k log k), space O(k))

Push (nums1[i] + nums2[0], i, 0) for the first min(k, m) values of i, and after popping (i, j) push only (i, j + 1). Each cell has exactly one parent, so no visited set is needed. This is the most common variant in interviews.

Generate all pairs and sort (time O(m × n × log(m × n)), space O(m × n))

Build every pair, sort by sum and take the first k. Only acceptable for tiny inputs.

Common mistakes

  • Pushing both neighbors without a visited set adds duplicate cells, so the same pair can appear twice in the output.
  • Checking the visited set when popping instead of when pushing lets duplicates pile up in the heap and wastes time.
  • Forgetting the len(result) < k condition, or stopping only when the heap is empty, returns too many pairs when k is small.
  • Assuming k is at most m × n; when k is larger, the loop must also stop when the heap runs out, which the while heap condition handles.

Frequently asked questions

Why use a heap for k smallest pairs?

The heap always holds the frontier of candidate pairs and hands you the smallest one in O(log k) time. Because both arrays are sorted, the next smallest pair must be a neighbor of one you already took, so the frontier stays small.

Why do we need a visited set?

Cell (i, j) can be reached from (i - 1, j) and from (i, j - 1). Without tracking visited cells, it would be pushed twice and the pair could be reported twice.

What is the time complexity of find k pairs with smallest sums?

O(k log k) with this frontier approach, since each of the k pops triggers at most two pushes on a heap of size O(k). It does not depend on the array lengths beyond the initial check.

How is this related to merging k sorted lists?

Each row of the sum grid is a sorted list, so the problem is a k-way merge where you stop after k elements. The heap plays exactly the same role in both problems.