Count Number of Nice Subarrays Problem
Description
LeetCode Problem 1248.
Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
Example 1:
Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
Example 2:
Input: nums = [2,4,6], k = 1
Output: 0
Explanation: There are no odd numbers in the array.
Example 3:
Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2
Output: 16
Constraints:
1 <= nums.length <= 500001 <= nums[i] <= 10^51 <= k <= nums.length
Solution
Approach: Prefix Counts of Odd Numbers
Only whether a number is odd matters, so think of each element as 1 (odd) or 0 (even). Let t be the number of odd numbers in the prefix ending at the current position. A subarray ending here has exactly k odd numbers when it starts right after a prefix that has t - k odd numbers.
So we walk the array once and keep cnt[c], the number of prefixes seen so far with exactly c odd numbers:
- Start with
cnt[0] = 1for the empty prefix, so subarrays that start at index0are counted. - For each element, update
t, addcnt[t - k]to the answer (whent >= k), then increasecnt[t].
The count t never exceeds n, so a plain array of size n + 1 works as the table. The even numbers around the odd ones are what make the counts large: in [2,2,2,1,2,2,1,2,2,2] with k = 2, a nice subarray must contain both 1s, so it can start at any of the 4 positions up to the first 1 and end at any of the 4 positions from the second 1, giving 4 · 4 = 16.
Complexity: O(n) time and O(n) space.
class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
# cnt[t] = how many prefixes of nums contain exactly t odd numbers
cnt = [0] * (len(nums) + 1)
cnt[0] = 1 # the empty prefix
ans = t = 0
for v in nums:
t += v & 1 # odd numbers in the prefix ending here
# a subarray ending here has k odd numbers when it starts after a prefix with t - k
if t >= k:
ans += cnt[t - k]
cnt[t] += 1
return ans