← Visualizers
Sliding Window · at‑most‑K → exactly‑K LeetCode 1248

Count Number of Nice Subarrays / visualized

A subarray is nice when it holds exactly k odd numbers. The magnitudes are noise: replace every value by value & 1 and the problem is LeetCode 930 on a 0/1 array with goal = k. Recognising that reduction is the whole skill here. And once reduced, the same wall appears: you cannot slide a window for exactly k, because odd == k is not monotone — growing right can jump past it, shrinking left can drop below it. But odd ≤ s is monotone, so exactly(k) = atMost(k) − atMost(k−1): run the same O(n) window twice and subtract. Inside each pass a valid window [l..r] banks r − l + 1 subarrays at once, one per suffix ending at r. The other standard solve is a prefix-count array — store how many prefixes have each odd-count and read off cnt[odd − k], the LC 560 shape; it is O(n) too, but it costs O(n) space and hides the monotonicity argument this page is about.

Execution

idle
the reduction, then the two passes
nums
& 1
odd —
≤ k
Σ 0
≤ k−1
Σ 0
exactly
Σ —
 
 
Press Run to begin.
0 / 0
Speed

Java · running line

inside the window · odd bits entering on the right evicted on the left suffixes just banked pass 1 · atMost(k) pass 2 · atMost(k−1) fallen out
O(n) time · O(1) space  ·  two linear passes, still O(n). nums[i] & 1 reduces this to LC 930 with goal = k; then exactly(k) = atMost(k) − atMost(k−1), because odd ≤ s is monotone and odd == k is not.