#1248

Count Number of Nice Subarrays

Medium atMost(k) − atMost(k−1)

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Count subarrays that contain exactly k odd numbers.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: count subarrays with exactly k odd numbers.

Why this works: counting "at most k" is easy with a window (each right end adds window-length subarrays). Exactly k = atMost(k) - atMost(k-1).

Example: [1, 1, 2, 1, 1], k = 3

atMost(3) = 14, atMost(2) = 12answer 2: [1,1,2,1] and [1,2,1,1]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Adding 1 per valid window instead of the window length — you'd count only one subarray per right end.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Sliding Window
🎬 Episode 10: video coming soon