Count Number of Nice Subarrays

medium

An array is nice if it contains exactly k odd numbers. Given an integer array nums and an integer k, return the number of nice contiguous subarrays.

Hints

Only the parity of each number matters — map odd to 1 and even to 0.
Then 'exactly k odd numbers' is 'sum exactly k' — the same as Binary Subarrays With Sum.
Count it as atMost(k) - atMost(k-1), where atMost(m) windows on the odd count.

Common doubts

Replace odd numbers with 1 and even with 0; a nice subarray is exactly one whose transformed sum is k. The identical atMost identity applies.
Once the window [left, right] has at most m odds, every subarray ending at right and starting in [left, right] also does — that's right - left + 1 of them.
No — they leave the odd count unchanged but still extend valid subarrays, which the right - left + 1 term accounts for.

Interview follow-ups

Track how many prefixes have each odd-count; for the current prefix odd-count c, add the number of earlier prefixes with count c - k. That's an alternate O(n) method.
Then you count subarrays with no odd numbers; the same identity holds with atMost(0) - atMost(-1) = atMost(0).

Fun facts

  • Nice Subarrays is Binary Subarrays With Sum wearing a parity costume — spotting the disguise is the whole trick.
  • The odd-as-1 mapping is a special case of 'indicator transform', turning many 'count items with property P' problems into subarray-sum problems.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: nums = [1,1,2,1,1], k = 3
Output: 2
The subarrays with exactly 3 odd numbers are [1,1,2,1] and [1,2,1,1].
Example 2
Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2
Output: 16
There are 16 subarrays containing exactly 2 odd numbers.
Constraints

- 1 <= nums.length <= 5 * 10^4 - 1 <= nums[i] <= 10^5 - 1 <= k <= nums.length

Solve this problem →