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

Count Number of Nice Subarrays

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

Odd → 1, then exactly(k) = atMost(k) − atMost(k − 1).

நடுத்தரம்ArrayHash TableMathSliding WindowPrefix Sum
LeetCode இல் திற ↗

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

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

Intuition

Replace each number by 1 if odd and 0 if even; now 'k odd numbers' means 'sum exactly k' — the same trick as binary subarrays: atMost(k) − atMost(k − 1).

Approach

  1. 1

    Sliding window over nums[i] % 2.

  2. 2

    Shrink while the odd count exceeds k.

  3. 3

    Add r − l + 1 per right edge.

  4. 4

    Subtract the atMost(k − 1) count.

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

atMost(k) − atMost(k−1)PythonO(n) time · O(1) space
class Solution:
    def getCountSubArray(self, nums, k):
        if k < 0:
            return 0
        cnt = 0
        total = 0
        l = 0
        for r in range(len(nums)):
            total += nums[r] % 2
            while total > k:
                total = total - nums[l] % 2
                l += 1
            if total <= k:
                cnt += r - l + 1
        return cnt

    def numberOfSubarrays(self, nums, k):
        return self.getCountSubArray(nums, k) - self.getCountSubArray(nums, k - 1)
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Count Number of Nice Subarrays — அடிக்கடி கேட்கப்படும் கேள்விகள்

Count Number of Nice Subarrays பின்னாலுள்ள intuition என்ன?

Replace each number by 1 if odd and 0 if even; now 'k odd numbers' means 'sum exactly k' — the same trick as binary subarrays: atMost(k) − atMost(k − 1).

Count Number of Nice Subarrays (LeetCode 1248) ஐ எப்படித் தீர்ப்பது?

1. Sliding window over nums[i] % 2. 2. Shrink while the odd count exceeds k. 3. Add r − l + 1 per right edge. 4. Subtract the atMost(k − 1) count.

Count Number of Nice Subarrays இன் time மற்றும் space complexity என்ன?

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

Count Number of Nice Subarrays இல் பொதுவான தவறுகள் என்ன?

Same atMost trick — only the value mapping changes.