Count Number of Nice Subarrays - Problem

Given an array of integers nums and an integer k, a continuous subarray is called nice if there are exactly k odd numbers in it.

Return the number of nice sub-arrays.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,1,2,1,1], k = 3
Output: 2
💡 Note: The only nice subarrays are [1,1,2,1] and [1,2,1,1], each containing exactly 3 odd numbers.
Example 2 — Smaller k
$ 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 — Single Element
$ Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2
Output: 16
💡 Note: Multiple subarrays contain exactly 2 odd numbers, including various combinations around the two odd numbers at positions 3 and 6.

Constraints

  • 1 ≤ nums.length ≤ 5 × 104
  • 1 ≤ nums[i] ≤ 105
  • 1 ≤ k ≤ nums.length

Visualization

Tap to expand
Count Number of Nice Subarrays INPUT nums array: 1 odd 1 odd 2 even 1 odd 1 odd i=0 i=1 i=2 i=3 i=4 k = 3 (target odd count) Find subarrays with 3 odds Nice Subarrays: [1,1,2,1] indices 0-3 3 odd numbers [1,2,1,1] indices 1-4 3 odd numbers ALGORITHM (Hash Map) 1 Initialize HashMap prefixCount[0] = 1 2 Track Odd Count oddCount += (num % 2) 3 Check for Nice result += map[oddCount-k] 4 Update Map map[oddCount]++ Prefix Count Map: oddCount | map value 0 | 1 (initial) 1 | 1 2 | 1 3 | 2 4 | 1 FINAL RESULT Answer: 2 Nice subarrays found: 2 Iteration Trace: i=0: num=1, odd=1, add map[1-3]=0 i=1: num=1, odd=2, add map[2-3]=0 i=2: num=2, odd=2, add map[2-3]=0 i=3: num=1, odd=3, add map[0]=1 i=4: num=1, odd=4, add map[1]=1 Total: 0+0+0+1+1 = 2 OK - Verified! Key Insight: Use prefix sum concept: Count odd numbers seen so far. A subarray [i,j] has exactly k odds if oddCount[j] - oddCount[i-1] = k. HashMap stores frequency of each prefix odd count. For current position, check how many previous positions had (currentOdd - k) odds. Time: O(n), Space: O(n) TutorialsPoint - Count Number of Nice Subarrays | Hash Map Approach
Asked in
Amazon 15 Google 12 Microsoft 8
32.0K Views
Medium Frequency
~25 min Avg. Time
892 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