medium +25 pts

Count Nice Subarrays

Count subarrays with exactly k odd numbers using a sliding window.

Given a list of positive integers `nums` and an integer `k`, return the number of subarrays that contain exactly `k` odd numbers. A subarray is a contiguous, non-empty sequence of elements within the array. Write a function `nice_subarrays(nums, k)` that returns an integer count. Examples: - `nice_subarrays([1,1,2,1,1], 3)` returns 2 (subarrays: [1,1,2,1] and [1,2,1,1]) - `nice_subarrays([2,4,6], 1)` returns 0 - `nice_subarrays([1,1,1], 2)` returns 2 ([1,1] and [1,1]) - `nice_subarrays([1,2,3,4,5], 2)` returns 4 (subarrays: [1,2,3], [1,2,3,4], [3,4,5], [2,3,4,5])

Constraints

1 <= len(nums) <= 10^5 1 <= nums[i] <= 10^9 0 <= k <= len(nums) Expected O(n) time and O(1) space (excluding output).

Example

>>> nice_subarrays([1,1,2,1,1], 3)
2
>>> nice_subarrays([2,4,6], 1)
0
>>> nice_subarrays([1,1,1], 2)
2
>>> nice_subarrays([1,2,3,4,5], 2)
4
25 points ~30 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

A subarray has at most k odd numbers if you can slide a window that shrinks when odd count exceeds k.
Compute count_of_at_most(k) - count_of_at_most(k-1).
In the sliding window, add right and subtract left while maintaining odd count.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.