Find K Pairs with Smallest Sums
LeetCode 373 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Best-first walk over the (i, j) grid with a min-heap.
ನಾನು Find K Pairs with Smallest Sums (LeetCode 373) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — K-way Merge ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
The smallest pair is (0, 0). From any pair (i, j) the next candidates are (i+1, j) and (i, j+1) — like walking a sorted grid. A min-heap explores the grid in order of sum; a seen set avoids pushing a cell twice.
Approach
- 1
Push (nums1[0] + nums2[0], 0, 0).
- 2
Pop the smallest, record the pair.
- 3
Push the right and down neighbours if unseen.
- 4
Stop after k pairs.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Min-heap grid walkPythonO(k log k) time
import heapq
class Solution:
def kSmallestPairs(self, nums1, nums2, k):
res = []
m = len(nums1)
n = len(nums2)
pq = [(nums1[0] + nums2[0], 0, 0)]
seen = {(0, 0)}
while pq and k != 0:
_, i, j = heapq.heappop(pq)
res.append([nums1[i], nums2[j]])
k -= 1
if i + 1 < m and (i + 1, j) not in seen:
seen.add((i + 1, j))
heapq.heappush(pq, (nums1[i + 1] + nums2[j], i + 1, j))
if j + 1 < n and (i, j + 1) not in seen:
seen.add((i, j + 1))
heapq.heappush(pq, (nums1[i] + nums2[j + 1], i, j + 1))
return resFind K Pairs with Smallest Sums — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Find K Pairs with Smallest Sums ಹಿಂದಿನ intuition ಏನು?
The smallest pair is (0, 0). From any pair (i, j) the next candidates are (i+1, j) and (i, j+1) — like walking a sorted grid. A min-heap explores the grid in order of sum; a seen set avoids pushing a cell twice.
Find K Pairs with Smallest Sums (LeetCode 373) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Push (nums1[0] + nums2[0], 0, 0). 2. Pop the smallest, record the pair. 3. Push the right and down neighbours if unseen. 4. Stop after k pairs.
Find K Pairs with Smallest Sums ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(k log k). Space: O(k). (Accepted approach: Min-heap grid walk.)
Find K Pairs with Smallest Sums ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Without the seen set, (i+1, j+1) gets pushed twice.