Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 373 · K-way Merge

Find K Pairs with Smallest Sums

LeetCode 373 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Best-first walk over the (i, j) grid with a min-heap.

நடுத்தரம்ArrayHeap (Priority Queue)
LeetCode இல் திற ↗

நான் 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. 1

    Push (nums1[0] + nums2[0], 0, 0).

  2. 2

    Pop the smallest, record the pair.

  3. 3

    Push the right and down neighbours if unseen.

  4. 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 res
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Find 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.