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.