Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 992 · Counting Subarrays (Exactly K = AtMost K − AtMost K−1)

Subarrays with K Different Integers

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

exactly(k) = atMost(k) − atMost(k − 1) with a count map.

கடினம்ArrayHash TableSliding WindowCounting
LeetCode இல் திற ↗

நான் Subarrays with K Different Integers (LeetCode 992) ஐ இப்படித் தீர்த்தேன் — Counting Subarrays (Exactly K = AtMost K − AtMost K−1) பேட்டர்னின் ஒரு கடினம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

'Exactly k distinct' is hard to slide directly, but 'at most k distinct' is easy: keep a count map, shrink while it has more than k keys, and every right edge adds r − l + 1 windows. Then exactly(k) = atMost(k) − atMost(k − 1).

Approach

  1. 1

    Add nums[r] to the map.

  2. 2

    While more than k distinct values, remove nums[l] (delete at zero) and advance.

  3. 3

    Add r − l + 1.

  4. 4

    Return atMost(k) − atMost(k − 1).

நான் எப்படித் தீர்த்தேன்

atMost(k) − atMost(k−1)PythonO(n) time · O(k) space
class Solution:
    def subarraysWithKDistinct(self, nums, k):
        def getCountOfSubArrays(nums, k):
            mpp = {}
            l = 0
            r = 0
            count = 0
            while r < len(nums):
                mpp[nums[r]] = mpp.get(nums[r], 0) + 1
                while len(mpp) > k:
                    mpp[nums[l]] -= 1
                    if mpp[nums[l]] == 0:
                        del mpp[nums[l]]
                    l += 1
                count += r - l + 1
                r += 1
            return count
        return getCountOfSubArrays(nums, k) - getCountOfSubArrays(nums, k - 1)
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Subarrays with K Different Integers — அடிக்கடி கேட்கப்படும் கேள்விகள்

Subarrays with K Different Integers பின்னாலுள்ள intuition என்ன?

'Exactly k distinct' is hard to slide directly, but 'at most k distinct' is easy: keep a count map, shrink while it has more than k keys, and every right edge adds r − l + 1 windows. Then exactly(k) = atMost(k) − atMost(k − 1).

Subarrays with K Different Integers (LeetCode 992) ஐ எப்படித் தீர்ப்பது?

1. Add nums[r] to the map. 2. While more than k distinct values, remove nums[l] (delete at zero) and advance. 3. Add r − l + 1. 4. Return atMost(k) − atMost(k − 1).

Subarrays with K Different Integers இன் time மற்றும் space complexity என்ன?

Time: O(n). Space: O(k). (Accepted approach: atMost(k) − atMost(k−1).)