Counting subarrays with exactly K of something is tricky directly. The trick: exactly(K) = at_most(K) - at_most(K - 1). Both sides are standard sliding-window problems.
What Is It?
Counting subarrays with exactly K distinct elements (or exactly K of some property) is hard with a bare sliding window, because the window can be invalid in two directions — too few or too many.
The insight: if you can count subarrays with at most K of something (easy with sliding window), then exactly(K) = at_most(K) - at_most(K - 1). You run the same sliding-window helper twice and subtract.
Why does this work? "At most K" counts subarrays with 0, 1, 2, ..., K of the thing. "At most K-1" counts subarrays with 0, 1, ..., K-1. Subtracting removes everything except exactly K.