Tap here to switch tabs
Problem
Ask
Submissions

Problem: Find K Pairs with Smallest Sums

med
30 min
Explore how to efficiently find the k pairs with the smallest sums from two sorted arrays by applying the k-way merge strategy. This lesson teaches you to assess problem statements and implement optimized solutions suitable for 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.

Tap here to switch tabs
Problem
Ask
Submissions

Problem: Find K Pairs with Smallest Sums

med
30 min
Explore how to efficiently find the k pairs with the smallest sums from two sorted arrays by applying the k-way merge strategy. This lesson teaches you to assess problem statements and implement optimized solutions suitable for 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.