Search⌘ K
AI Features

Find K Pairs with Smallest Sums

Explore how to find the k pairs with the smallest sums between two sorted integer arrays using the K-way merge approach. This lesson helps you understand the problem constraints and implement an efficient solution to select pairs with the minimal combined values, a common pattern in coding interviews.

Statement

You are given two integer arrays, list1 and list2, sorted in non-decreasing order, and an integer, k.

A pair (u, v)(u, \space v) is defined as one element uu chosen from list1 and one element vv chosen from list2.

Your task is to return the k pairs (u1, v1),(u2, v2),...,(uk, vk)(u1, \space v1), (u2, \space v2), ..., (uk, \space vk) whose sums u1+v1,u2+v2,...,uk+vku1 + v1, u2 + v2, ..., uk + vk are the smallest among all possible such pairs.

Note: If multiple pairs have the same sum, any order among them is acceptable.

Constraints:

  • 11 \leq list1.length, list2.length \leq 500500

  • 104-10^4 \leq list1[i], list2[i] \leq 10410^4

  • 11 \leq kk \leq 10310^3

  • Input lists should be sorted in ascending order.

  • If the value of kk exceeds the total number of valid pairs that may be formed, return all the pairs.

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Find K Pairs with Smallest Sums

1.

What is the output if the following lists and value of k is given as input?

list1 = [1, 11, 20, 35, 300]

list2 = [1, 2, 300]

k = 5

A.

pairs = [[1, 1], [1, 2], [1, 300], [11, 1], [11, 2]]

B.

pairs = [[1, 1], [1, 2], [11, 1], [11, 2], [11, 300]]

C.

pairs = [[1, 1], [1, 2], [11, 1], [11, 2], [20, 2]]

D.

pairs = [[1, 1], [1, 2], [11, 1], [11, 2], [20, 1]]


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in the following coding playground.

JavaScript
usercode > Solution.js
import { MinHeap, MaxHeap } from "./Heap.js";
/* The following definition is for MinHeap.
You can use the same methods for MaxHeap.
class MinHeap {
size(); // return number of elements
peek(); // return top element without removing
push(val); // insert element
pop(); // remove and return top element
}
*/
function kSmallestPairs(list1, list2, k){
// Replace this placeholder return statement with your code
return [];
}
export {
kSmallestPairs
}
Find K Pairs with Smallest Sums