Count Number of Nice Subarrays (LeetCode 1248): Solution and Explanation

Medium
Array
Hash Table
Math
Sliding Window
Prefix Sum

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

  1. Set left = odds = gap = count = 0.
  2. For each right, if nums[right] is odd, add one to odds and set gap = 0.
  3. While odds == k: if nums[left] is odd, subtract one from odds. Move left right and add one to gap.
  4. Add gap to count.
  5. Return count.

Step-by-step example

nums = [1,1,2,1,1], k = 3
  1. Right ends 0, 1 and 2 bring in two odds and an even. odds = 2 < 3, so gap = 0 and nothing is added.
  2. Right end 3 is the third odd. gap resets to 0. The window [0, 3] holds 3 odds, so left steps past index 0, which is odd: odds = 2, gap = 1. Add 1: the subarray [1,1,2,1].
  3. Right end 4 is odd: odds = 3, gap = 0. The window [1, 4] holds 3 odds, so left steps past index 1 (odd): odds = 2, gap = 1. Add 1: the subarray [1,2,1,1].
  4. 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 count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

right visits each index once and left moves forward at most n times overall.

Space

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 gap on 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 == 1 in a language where negative odd numbers give -1. The constraints keep values positive here, but % 2 != 0 is safer in general.
  • Checking odds > k in the while loop instead of odds == 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.