Ad platform~30 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-1248, lc-930at-most-k · prefix-sum-hashmap · sliding-window-variable
An ad platform shows each campaign to many people. Every showing is an impression, and the log records each one in order: 1 if the person clicked, 0 if not.
The pacing team decides how fast a campaign spends its budget. To model how clicks cluster, they study stretches of consecutive impressions that hold exactly k clicks. A short stretch with k clicks means a burst of interest; a long one means a slow period. For each campaign log and each k, the team wants the number of such stretches.
Write count_k_clicks(clicks, k).
clicks[i] is 1 if impression i was clicked and 0 if it was not.i to impression j with i ≤ j.k clicks. Stretches may overlap, and every pair (i, j) counts once.k is 0, count the stretches with no clicks at all.k clicks, for example when k is larger than the total number of clicks, return 0. The log is never empty.Input: clicks = [1, 0, 1, 0, 0, 1], k = 2
Output: 5Count the stretches with at most 2 clicks and the stretches with at most 1 click that end at each right. The difference is the number with exactly 2.
| right | Click | At most 2: left | At most 2: stretches | At most 1: left | At most 1: stretches | Exactly 2 | Total |
|---|---|---|---|---|---|---|---|
| 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 |
| 1 | 0 | 0 | 2 | 0 | 2 | 0 | 0 |
| 2 | 1 | 0 | 3 | 1 | 2 | 1 | 1 |
| 3 | 0 | 0 | 4 | 1 | 3 | 1 | 2 |
| 4 | 0 | 0 | 5 | 1 | 4 | 1 | 3 |
| 5 | 1 | 1 | 5 | 3 | 3 | 2 | 5 |
Over the whole log, 20 stretches have at most 2 clicks and 15 have at most 1, so 5 have exactly 2.
Input: clicks = [0, 1, 0, 0], k = 0
Output: 4The stretches with no clicks are 0 at the start, and 0, 0 and 0, 0 at the end.
Input: clicks = [1, 0, 1], k = 3
Output: 0The whole log holds only 2 clicks, so no stretch holds 3.
1 ≤ clicks.length ≤ 10^5clicks[i] is 0 or 10 ≤ k ≤ 10^5Checking every pair of start and end is O(n^2): about 5 × 10^9 steps at n = 10^5. Aim for O(n).
Read the answer's size too. With no clicks and k = 0, every stretch counts: n(n + 1) / 2 = 5,000,050,000, beyond a 32-bit integer. Use a 64-bit count in Java and C++.