Find K Pairs with Smallest Sums
Problem Statement
You get two integer arrays, nums1 and nums2, and both are sorted from smallest to largest. A pair takes one value from nums1 and one value from nums2. Its sum is the two values added together.
Return the k pairs with the smallest sums. Each pair must use a different combination of positions (one position in nums1, one in nums2). If there are fewer than k pairs in total, return all of them. The order of the answer does not matter.
Two sorted integer arrays nums1 and nums2, and an integer k.
A list of pairs [u, v] (u from nums1, v from nums2) with the smallest sums, at most k of them.
The sums are 3, 5 and 7 for these three pairs. The next sum is 9, so these are the three smallest.
The two 1s in nums1 are different positions, so both pairs [1,1] count. Their sum is 2.
- • 1 ≤ nums1.length, nums2.length ≤ 10^5
- • −10^9 ≤ nums1[i], nums2[i] ≤ 10^9
- • nums1 and nums2 both are sorted in non-decreasing order
- • 1 ≤ k ≤ 10^4
- • k ≤ nums1.length · nums2.length
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
List every pair, sort them by sum, and keep the first k
Scan the pairs, keep a max-heap of the k smallest sums, and skip the rest of a row once it is too big
Min-heap of (i, j) pairs: start each row at j = 0, pop k times, push the next pair in the same row
Build all m · n pairs, sort them by sum, and return the first k. Sorting every pair is wasteful when only k of them are needed.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like K-way Merge translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.