Count Number of Nice Subarrays

Medium Topics Company Tags

A nice subarray is a nonempty contiguous portion of nums containing exactly k odd numbers. Return the total number of nice subarrays. Different start or end positions count separately, even when their values are the same.

Example 1:

Input: nums = [2,1,2]
k = 1

Output: 4

Explanation: The four qualifying subarrays are [1], [2,1], [1,2], and [2,1,2]. Each contains exactly one odd number.

Example 2:

Input: nums = [1,1,1]
k = 2

Output: 2

Explanation: The two length-2 windows each contain exactly two odd numbers. The full array contains three odds and does not qualify.

Example 3:

Input: nums = [2,4]
k = 1

Output: 0

Explanation: Both values are even, so no subarray contains the required one odd number.

Constraints:

  • 1 <= nums.length <= 50000
  • 1 <= nums[i] <= 100000
  • 1 <= k <= nums.length


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.