Count Number of Nice Subarrays - Problem
You're given an array of integers nums and an integer k. Your task is to find the number of "nice" subarrays.

A subarray is considered nice if it contains exactly k odd numbers. A subarray is a contiguous sequence of elements from the array.

For example, given nums = [1, 1, 2, 1, 1] and k = 3, we need to find all subarrays that contain exactly 3 odd numbers. The subarrays [1, 1, 2, 1] and [1, 2, 1, 1] both contain exactly 3 odd numbers, so they are "nice".

Goal: Return the total count of nice subarrays in the given array.

Input & Output

example_1.py β€” Basic Case
$ Input: nums = [1,1,2,1,1], k = 3
β€Ί Output: 2
πŸ’‘ Note: The nice subarrays are [1,1,2,1] and [1,2,1,1]. Both contain exactly 3 odd numbers.
example_2.py β€” Single Element
$ Input: nums = [2,4,6], k = 1
β€Ί Output: 0
πŸ’‘ Note: All numbers are even, so no subarray can have exactly 1 odd number.
example_3.py β€” All Odd Numbers
$ Input: nums = [1,3,5], k = 3
β€Ί Output: 1
πŸ’‘ Note: Only the entire array [1,3,5] contains exactly 3 odd numbers.

Visualization

Tap to expand
The Transformation Strategy1Step 1Transform2Step 2Prefix Sum3Step 3Hash Map4Step 4CountExample Walkthrough: [1,1,2,1,1], k=3Original:11211Binary:11011Prefix Sum:12234Hash Map finds: sum=3 matches sum=0 (diff=3) and sum=4 matches sum=1 (diff=3)
Understanding the Visualization
1
Binary Transformation
Convert the number array to binary: odd numbers become 1, even numbers become 0
2
Prefix Sum Tracking
Maintain running count of 1s encountered so far (prefix sum)
3
Hash Map Magic
For each position, check if there's a previous position where prefix sum differs by exactly k
4
Count Valid Pairs
Each valid pair represents the start and end of a nice subarray
Key Takeaway
🎯 Key Insight: By transforming the problem to prefix sums, we reduce the complexity from O(n²) checking all subarrays to O(n) using mathematical properties and hash map lookups.

Time & Space Complexity

Time Complexity
⏱️
O(n)

Single pass through the array with O(1) hash map operations

n
2n
βœ“ Linear Growth
Space Complexity
O(n)

Hash map stores at most n different prefix sum values

n
2n
⚑ Linearithmic Space

Constraints

  • 1 ≀ nums.length ≀ 5 Γ— 104
  • 1 ≀ nums[i] ≀ 105
  • 1 ≀ k ≀ nums.length
  • All elements are positive integers
Asked in
Facebook 85 Amazon 72 Google 68 Microsoft 45 Apple 38
87.5K Views
High Frequency
~18 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen