Count Number of Nice Subarrays
Count Number of Nice Subarrays is LeetCode 1248 (Medium). Given an array nums and an integer k, a contiguous subarray is nice if it contains exactly k odd numbers. Return the number of nice subarrays.
numshas up to 50,000 elements, so checking all of its roughly 1.25 · 10⁹ subarrays is too slow.- Only whether a number is odd matters, never its value.
- 1 <= nums.length <= 50000
- 1 <= nums[i] <= 10^5
- 1 <= k <= nums.length
Intuition
Look at a nice subarray by the odd numbers inside it. It holds k odds that sit next to each other in the list of odds, and it may also hold even numbers on either side. Stretching it over more evens never changes its odd count.
So for one fixed group of k odds, the subarray can start anywhere from just after the previous odd up to the first odd of the group, and end anywhere from the last odd up to just before the next one. The count is starts × ends, and one pass adds it up:
starts: found when the window first holdskodds, by slidingleftup to and past the first odd.- Every right end: adds
starts, until the next odd begins a new group.
"Count subarrays with exactly k of something" where adding an element can only keep or raise the count. Exactly-k has no single window boundary, but the number of valid starts for each right end can be carried along and reset whenever the group of k changes.
Approach
Before reading on, fix the right end of a subarray and ask: which start positions give exactly k odds? Then ask how that set changes when the next number is even, and when it is odd. Aim for O(n) time and O(1) space.
Two ways to solve it
Keep how many start positions give exactly k odds for the current right end, and add it each step.
- One pass: no helper function.
- Reset: the count restarts at every new odd.
A plain window counts subarrays with at most k odds; subtract the count for at most k − 1.
- Familiar: the same helper as other exactly-k counts.
- Cost: two passes over the array.
Both run in O(n) with O(1) memory. The one-pass version counts start positions directly; the at-most version is the classic trick and needs no new idea if you already know it from a similar problem. The steps, code and live demo follow the one-pass version, and the at-most code comes after the demo.
Grow the window one number at a time
Move across nums. When the new number is odd, add 1 to odd and set starts to 0, because the start positions counted so far belonged to a different group of k odds.
Shrink while the window holds exactly k odds
While odd == k, add 1 to starts and move left one step, taking nums[left] out of the count. Each step proves one more start position works. The loop ends right after left passes an odd number, when the window drops to k − 1 odds.
Add the start count for this right end
Add starts to the answer. After an odd number it is the fresh count; after an even number it is unchanged, because each of those starts still gives exactly k odds when one more even number joins on the right.
Code in Python, C++ and Java
starts resets to 0. The window has only 1 odd, fewer than 3, so no subarray ending here is nice.starts resets to 0. The window has only 2 odds, fewer than 3, so no subarray ending here is nice.starts resets to 0. The window has only 1 odd, fewer than 2, so no subarray ending here is nice.At most k minus at most k − 1
at_most(m) slides a window that never holds more than m odds. For each right end, every start from left to right is valid, which adds right - left + 1. Subarrays with at most k odds, minus those with at most k − 1, leaves exactly k.
Common pitfalls
Adding one per right end instead of the start count
while odd > k:
odd -= nums[left] % 2
left += 1
if odd == k:
answer += 1while odd == k:
starts += 1
odd -= nums[left] % 2
left += 1
answer += startsA right end can pair with several starts, one for each even number in front of the first odd. On [2,1,2] with k = 1 the nice subarrays are [2,1], [1], [2,1,2] and [1,2], so the answer is 4, but adding 1 per right end gives 2.
Keeping the old start count after a new odd
if x % 2:
odd += 1if x % 2:
odd += 1
starts = 0A new odd starts a new group of k odds, and the shrink loop counts its starts from scratch. Without the reset the old count is added on top: [1,2,1,2,1] with k = 1 should give 8, but the leftover starts push it to 13.
Edge cases
k odd numbers in the arrayodd never reaches k, so the shrink loop never runs, starts stays 0 and the answer is 0, as in [2,4,6] with k = 1.
Complexity
right moves across the array once, and left only moves forward, so each index enters and leaves the window at most once. Four counters are all the memory used.Count Number of Nice Subarrays FAQ
Is this the same as Binary Subarrays With Sum?
Yes, once each number is replaced by 1 if odd and 0 if even: it becomes Binary Subarrays With Sum with goal = k, and that page walks through the at-most window step by step.
Can a prefix count with a hash map solve it?
Yes. Keep how many prefixes so far had each number of odds, starting with one empty prefix that has 0. At each index, add the count for odds so far − k, then record the current prefix. It is one pass in O(n), but it stores up to n + 1 counts.