Count Number of Nice Subarrays (LeetCode 1248): Solution and Explanation
Given an integer array and k, count the contiguous subarrays that contain exactly k odd numbers.
Intuition
Only parity matters, so read the array as a row of odd and even markers. A nice subarray is any stretch that covers exactly k of the odd markers.
Grow a window to the right. Once it holds exactly k odds, the window can lose any evens in front of its first odd and still hold k odds. Each of those starts, plus the first odd itself, gives a nice subarray ending at right.
Slide left past those starts until the first odd drops out, and remember how many you passed in gap. Now the window holds k - 1 odds again.
While the next elements are even, the same gap starts keep working, so add gap at every right end. When a new odd arrives, those starts now cover k + 1 odds, so gap resets to 0 and the slide happens again.
Approach: Sliding window with a start counter
- Set
left = odds = gap = count = 0. - For each
right, ifnums[right]is odd, add one tooddsand setgap = 0. - While
odds == k: ifnums[left]is odd, subtract one fromodds. Moveleftright and add one togap. - Add
gaptocount. - Return
count.
Step-by-step example
nums = [1,1,2,1,1], k = 3
- Right ends 0, 1 and 2 bring in two odds and an even.
odds = 2 < 3, sogap = 0and nothing is added. - Right end 3 is the third odd.
gapresets to 0. The window[0, 3]holds 3 odds, soleftsteps past index 0, which is odd:odds = 2,gap = 1. Add 1: the subarray[1,1,2,1]. - Right end 4 is odd:
odds = 3,gap = 0. The window[1, 4]holds 3 odds, soleftsteps past index 1 (odd):odds = 2,gap = 1. Add 1: the subarray[1,2,1,1]. - The answer is 2.
Code: Python, Java, C++
1class Solution:
2 def numberOfSubarrays(self, nums: List[int], k: int) -> int:
3 left = odds = gap = count = 0
4 for right in range(len(nums)):
5 if nums[right] % 2 == 1:
6 odds += 1
7 gap = 0
8 while odds == k:
9 if nums[left] % 2 == 1:
10 odds -= 1
11 left += 1
12 gap += 1
13 count += gap
14 return count1class Solution {
2 public int numberOfSubarrays(int[] nums, int k) {
3 int left = 0, odds = 0, gap = 0, count = 0;
4 for (int right = 0; right < nums.length; right++) {
5 if (nums[right] % 2 == 1) {
6 odds++;
7 gap = 0;
8 }
9 while (odds == k) {
10 if (nums[left] % 2 == 1) odds--;
11 left++;
12 gap++;
13 }
14 count += gap;
15 }
16 return count;
17 }
18}1class Solution {
2public:
3 int numberOfSubarrays(vector<int>& nums, int k) {
4 int left = 0, odds = 0, gap = 0, count = 0;
5 for (int right = 0; right < (int)nums.size(); right++) {
6 if (nums[right] % 2 == 1) {
7 odds++;
8 gap = 0;
9 }
10 while (odds == k) {
11 if (nums[left] % 2 == 1) odds--;
12 left++;
13 gap++;
14 }
15 count += gap;
16 }
17 return count;
18 }
19};Time and space complexity
O(n)
right visits each index once and left moves forward at most n times overall.
O(1)
Only the two edges and three counters are stored.
Other approaches
Prefix odd counts with a hash map (time O(n), space O(n))
Keep a running count of odds and a map from each running count to how often it appeared. At each index add seen[odds - k]. Since the counts only go up, an array of size n + 1 works in place of the map.
At most k minus at most k - 1 (time O(n), space O(1))
Count subarrays with at most k odds using a shrinking window, do the same for k - 1, and subtract. Two passes, same idea as Binary Subarrays With Sum.
Positions of the odd numbers (time O(n), space O(n))
Store the indices of every odd number. For each group of k consecutive odds, multiply the number of evens to its left plus one by the number of evens to its right plus one.
Common mistakes
- Resetting
gapon every element instead of only when an odd arrives. The evens after the window must reuse the same starts. - Counting the window once per right end with a plain shrinking window, which misses the extra starts made by leading evens.
- Using
nums[i] % 2 == 1in a language where negative odd numbers give -1. The constraints keep values positive here, but% 2 != 0is safer in general. - Checking
odds > kin the while loop instead ofodds == k, which never slides when the window first reaches k.
Frequently asked questions
Why does gap reset to zero when a new odd arrives?
The starts counted in gap gave exactly k odds before the new odd. With the new odd they would give k + 1, so none of them work anymore and a new set of starts must be found.
Is this the same problem as Binary Subarrays With Sum?
Yes, after mapping odd to 1 and even to 0. Counting subarrays with exactly k odds is counting binary subarrays whose sum is k.
Can the answer overflow a 32-bit integer?
The largest count is about n squared over 4 for n = 50,000, roughly 625 million, which fits in a signed 32-bit integer.