Count Number of Nice Subarrays

Given an array of integers `nums` and an integer `k`, a continuous subarray is called **nice** if there are exactly `k` odd numbers in it. Return the number of nice subarrays.

30:00

Count Number of Nice Subarrays
medium
Free written solution
Topics
Companies

Given an array of integers nums and an integer k, a continuous subarray is called nice if there are exactly k odd numbers in it.

Return the number of nice subarrays.

Example 1:
Input: {"nums":[1,1,2,1,1],"k":3}
Output: 2
Constraints:
  • 1≤nums.length≤500001 \leq \text{nums.length} \leq 50000

  • 1≤nums[i]≤1051 \leq \text{nums}[i] \leq 10^5

  • 1≤k≤nums.length1 \leq k \leq \text{nums.length}

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,1,2,1,1],"k":3}

Only parity matters. Grow a window; once it holds 3 odd numbers, count how many starts can be dropped before the first odd.

odds in window: need 3

#1
#2
#3

nums (orange = odd)

1odd
1odd
2even
1odd
1odd

0

1

2

3

4

odds

-

gap

-

count

0

Variables
VariableValue
left0
odds0
gap0
count0
k3
DepthFunction Call
Stack empty
0/15