MediumNo. 0373
Find K Pairs with Smallest Sums — LeetCode 373 Python Solution
- Pattern
- Heap / Priority Queue
- Topics
- Array, Heap (Priority Queue)
- On a study list
- Top Interview 150
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 0215 | Kth Largest Element in an Array | Medium |
| 0218 | The Skyline Problem | Hard |
| 0407 | Trapping Rain Water II | Hard |
| 0506 | Relative Ranks | Easy |
| 0675 | Cut Off Trees for Golf Event | Hard |
| 0912 | Sort an Array | Medium |
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.