MediumNo. 0373

Find K Pairs with Smallest Sums — LeetCode 373 Python Solution

Topics
Array, Heap (Priority Queue)
On a study list
Top Interview 150
Reading time
3 min

The problem

You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k. Define a pair (u, v) which consists of one element from the first array and one element from the second array.

Example

Input
nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Output
[[1,2],[1,4],[1,6]]
Explanation
The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]

Python solution

PythonSolution
class Solution:
    def kSmallestPairs(
        self, nums1: List[int], nums2: List[int], k: int
    ) -> List[List[int]]:
        q = [[u + nums2[0], i, 0] for i, u in enumerate(nums1[:k])]
        heapify(q)
        ans = []
        while q and k > 0:
            _, i, j = heappop(q)
            ans.append([nums1[i], nums2[j]])
            k -= 1
            if j + 1 < len(nums2):
                heappush(q, [nums1[i] + nums2[j + 1], i, j + 1])
        return ans

Complexity

Time
O(n log n)
Space · auxiliary
O(n)

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 373. Find K Pairs with Smallest Sums is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0215Kth Largest Element in an ArrayMedium
0218The Skyline ProblemHard
0407Trapping Rain Water IIHard
0506Relative RanksEasy
0675Cut Off Trees for Golf EventHard
0912Sort an ArrayMedium

Frequently asked questions

How hard is LeetCode 373. Find K Pairs with Smallest Sums?

LeetCode 373. Find K Pairs with Smallest Sums is rated Medium on LeetCode.

What is the time complexity of LeetCode 373. Find K Pairs with Smallest Sums?

The Python solution on this page runs in O(n log n).

What is the space complexity of LeetCode 373. Find K Pairs with Smallest Sums?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 373. Find K Pairs with Smallest Sums cover?

LeetCode 373. Find K Pairs with Smallest Sums is tagged Array and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.