Coding Interview PatternsCount Number of Nice Subarrays
MediumSliding Window
Count Number of Nice Subarrays
Explanation & Solution
Description
Given an array of integers nums and an integer k, return the number of nice subarrays.
A nice subarray is a contiguous subarray with exactly k odd numbers.
Input:nums = [1,1,2,1,1], k = 3
0
1
1
1
2
2
3
1
4
1
Output: 2
Explanation: The only nice subarrays with exactly 3 odd numbers are [1,1,2,1] and [1,2,1,1].
Constraints
1 <= nums.length <= 5 * 10^41 <= nums[i] <= 10^51 <= k <= nums.length
Approach
Sliding Window pattern
1. The "Exactly K" = "At Most K" minus "At Most K-1" Trick
- Counting subarrays with exactly K odd numbers directly is tricky with a sliding window.
- Instead, we compute:
atMost(k) - atMost(k - 1). atMost(k)counts all subarrays with 0, 1, 2, ..., or k odd numbers.- Subtracting
atMost(k - 1)removes those with fewer than k odds, leaving exactly k.
2. The atMost Helper
- Initialize
left = 0,odds = 0(count of odd numbers in window), andcount = 0. - Iterate
rightacross the array. Ifnums[right]is odd, incrementodds.
3. Shrink When Too Many Odds
- While
odds > goal, check ifnums[left]is odd (if so, decrementodds), then incrementleft. - This contracts the window until we have at most
goalodd numbers.
4. Count Valid Subarrays
- After adjusting, every subarray ending at
rightand starting from any index in[left, right]has at mostgoalodd numbers. - Add
right - left + 1tocount.
5. Combine the Results
- Return
atMost(k) - atMost(k - 1)to get the count of subarrays with exactlykodd numbers.
🧠 Key Insight
The atMost subtraction pattern converts an "exactly K" problem into two simpler "at most K" problems, each solvable with a standard sliding window. This runs in O(n) time (two passes) and O(1) space. The key observation is that exactly(k) = atMost(k) - atMost(k-1) because the set of subarrays with at most k odds includes all subarrays with at most k-1 odds as a subset.
Visualization
Input:
[1, 1, 2, 1, 1], k = 3
—
Press ▶ or use ← → to step through
Left (L)Right (R)WindowDone
7 steps