LeetCode #1248 Medium

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.

  • nums has 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.
Constraints
  • 1 <= nums.length <= 50000
  • 1 <= nums[i] <= 10^5
  • 1 <= k <= nums.length
sliding-windowprefix-sumarray
Open on LeetCode ↗
02

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 holds k odds, by sliding left up to and past the first odd.
  • Every right end: adds starts, until the next odd begins a new group.
How to spot this pattern

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

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

04

Code in Python, C++ and Java

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def numberOfSubarrays(self, nums: List[int], k: int) -> int:
▶6 answer = left = odd = starts = 0
▶7 for x in nums:
▶8 if x % 2:
▶9 odd += 1
▶10 starts = 0
▶11 while odd == k:
▶12 starts += 1
▶13 odd -= nums[left] % 2
▶14 left += 1
▶15 answer += starts
▶16 return answer
1odd01odd1221odd31odd40odds in window0valid starts0answerneed exactly 3 odd numbers per subarray
k3
answer0
The values do not matter, only which ones are odd, so the odd numbers are tagged. For each right end, the shaded tiles will show where a nice subarray ending there can begin.
1odd01odd1221odd31odd41odds0so far+0starts=0answer1 is odd → 1 of 3 odds, no start works yet
x1odd
odd1
starts0
answer0
A new odd number starts a new group, so starts resets to 0. The window has only 1 odd, fewer than 3, so no subarray ending here is nice.
1odd01odd1221odd31odd42odds0so far+0starts=0answer1 is odd → 2 of 3 odds, no start works yet
x1odd
odd2
starts0
answer0
A new odd number starts a new group, so starts resets to 0. The window has only 2 odds, fewer than 3, so no subarray ending here is nice.
1odd01odd1221odd31odd42odds0so far+0starts=0answer2 is even → still no nice subarray
x2even
odd2
starts0
answer0
The window still has fewer than 3 odds, so there is nothing to add.
1odd01odd1221odd31odd43odds in window0valid starts0answer1 is odd → 3 odds in the window: nice
x1odd
odd3
starts0reset
This odd number completes a group of 3. The old start count belonged to the previous group, so it resets to 0, and the shrink loop counts the starts for this group.
1odd01odd1221odd31odd42odds in window1valid starts0answerstart at index 0 works → drop odd 1, stop
starts1
left1
odd2
The window from index 0 to 3 has exactly 3 odds, so index 0 is a valid start. That number was odd, so dropping it leaves 2 odds: every start further right would miss one, and the loop stops with 1 start.
1odd01odd1221odd31odd42odds0so far+1starts=1answeradd 1 nice subarray ending at index 3
answer1
Each shaded tile is a start that gives a nice subarray ending at index 3, so 1 more are counted.
1odd01odd1221odd31odd43odds in window0valid starts1answer1 is odd → 3 odds in the window: nice
x1odd
odd3
starts0reset
This odd number completes a group of 3. The old start count belonged to the previous group, so it resets to 0, and the shrink loop counts the starts for this group.
1odd01odd1221odd31odd42odds in window1valid starts1answerstart at index 1 works → drop odd 1, stop
starts1
left2
odd2
The window from index 1 to 4 has exactly 3 odds, so index 1 is a valid start. That number was odd, so dropping it leaves 2 odds: every start further right would miss one, and the loop stops with 1 start.
1odd01odd1221odd31odd42odds1so far+1starts=2answeradd 1 nice subarray ending at index 4
answer2
Each shaded tile is a start that gives a nice subarray ending at index 4, so 1 more are counted.
1odd01odd1221odd31odd42odds in window1valid starts2answeranswer: 2
answer2
2 nice subarrays. Each group of 3 odds contributed its number of starts once for every right end it could reach.
05

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.

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def numberOfSubarrays(self, nums: List[int], k: int) -> int:
▶6 def at_most(m):
▶7 left = odd = total = 0
▶8 for right, x in enumerate(nums):
▶9 odd += x % 2
▶10 while odd > m:
▶11 odd -= nums[left] % 2
▶12 left += 1
▶13 total += right - left + 1
▶14 return total
▶15 
▶16 return at_most(k) - at_most(k - 1)
06

Common pitfalls

Adding one per right end instead of the start count

✗ Wrong
while odd > k:
    odd -= nums[left] % 2
    left += 1
if odd == k:
    answer += 1
✓ Right
while odd == k:
    starts += 1
    odd -= nums[left] % 2
    left += 1
answer += starts

A 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

✗ Wrong
if x % 2:
    odd += 1
✓ Right
if x % 2:
    odd += 1
    starts = 0

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

07

Edge cases

Fewer than k odd numbers in the array

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

08

Complexity

Time
O(n)
Space
O(1)
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.
09

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.