Tensorum
LeetCode 1248 · Counting Subarrays (Exactly K = AtMost K − AtMost K−1)

Count Number of Nice Subarrays

LeetCode 1248 · Medium · solution, intuition & step-by-step walkthrough

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

MediumArrayHash TableMathSliding WindowPrefix Sum
79 msruntime · beats 5%
57.7 MBmemory · beats 100%
1approach
1accepted runs · last 5 May 2024

This is how I solved Count Number of Nice Subarrays (LeetCode 1248), a medium problem from the Counting Subarrays (Exactly K = AtMost K − AtMost K−1) pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a 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.

How I solved it

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)
Loading the step-through…

Count Number of Nice Subarrays — FAQ

What is the intuition behind Count Number of Nice Subarrays?

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

How do you solve 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.

What is the time and space complexity of Count Number of Nice Subarrays?

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

What are common mistakes in Count Number of Nice Subarrays?

Same atMost trick — only the value mapping changes.