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 Nice Subarrays: Find subarrays with exactly k=3 odd numbersInput Array:11211oddoddevenoddoddNice Subarrays (k=3):[1,1,2,1] - 3 odds ✓[1,2,1,1] - 3 odds ✓Result: 2 nice subarrays foundEach subarray contains exactly 3 odd numbers
Understanding the Visualization
1
Input
Array with mixed odd/even numbers and target k
2
Process
Find all continuous subarrays with exactly k odds
3
Output
Count of valid subarrays
Key Takeaway
🎯 Key Insight: Transform the counting problem by focusing on odd/even patterns rather than actual values
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