medium +25 pts

Count Nice Subarrays

Count subarrays with exactly k odd numbers using an efficient sliding window.

Write a function `count_nice_subarrays(nums, k)` that takes a list of integers `nums` and an integer `k` (0 <= k <= len(nums)). It should return the number of contiguous subarrays that contain exactly `k` odd numbers. Odd numbers are integers not divisible by 2. The array may contain negative numbers and zeros. The function must run in O(n) time and O(1) extra space.

Constraints

1 <= len(nums) <= 10^5 -10^4 <= nums[i] <= 10^4 0 <= k <= len(nums)

Example

>>> count_nice_subarrays([1,1,2,1,1], 3)
2
>>> count_nice_subarrays([2,4,6], 1)
0
>>> count_nice_subarrays([2,2,2,1,2,2,1,2,2], 2)
12
25 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Convert each number to 1 if odd, 0 if even, then think of counting subarrays with sum exactly k.
Use the sliding window technique with two pointers to count subarrays with at most k odd numbers, then subtract.
Remember to handle k=0 carefully: zeros-only subarrays are counted.
Try using prefix sums and a dictionary if the sliding window gets tricky.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.