Count Number of Nice Subarrays - Problem
You're given an array of integers
A subarray is considered nice if it contains exactly
For example, given
Goal: Return the total count of nice subarrays in the given array.
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
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
β Linear Growth
Space Complexity
O(n)
Hash map stores at most n different prefix sum values
β‘ Linearithmic Space
Constraints
- 1 β€ nums.length β€ 5 Γ 104
- 1 β€ nums[i] β€ 105
- 1 β€ k β€ nums.length
- All elements are positive integers
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code