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.