Find K Pairs with Smallest Sums — LeetCode 373 Python Solution
- Problem
- #373
- Pattern
- Heap / Priority Queue
- 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
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(n) auxiliary |
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
On a study list
This problem is on Top Interview 150.
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.