Count the number of contiguous subarrays that contain exactly odd numbers.
Nice Subarrays
gfgGiven an integer array nums and an integer k, count how many contiguous subarrays contain exactly k odd numbers.
A subarray is a contiguous non-empty portion of the array. A subarray is considered nice if it contains exactly k elements whose values are odd.
Input Format
nums: an integer arrayk: a positive integer
Return the number of contiguous subarrays with exactly k odd numbers.
Output Format
- Return a single integer: the number of nice subarrays.
Constraints
- The subarray must be contiguous.
- Count subarrays with exactly
kodd elements. numsis non-empty in the original problem formulation.- A linear or near-linear solution is expected for interview use.
Example 1
Input
nums = [1,1,2,1,1], k = 3
Output
2
Explanation
The nice subarrays 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, so no subarray can contain exactly 1 odd number.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.