6/32
Part 2 of 6 · A fixed windowLearn and do

A Counter counts copies, so a key twice in the window stays counted

The state doesn't have to be a sum. It can be anything you can update when one entry comes in and one goes out.

How many different clients sent requests in each window of k? A set of keys looks right. Here it is next to a count per key, on the log ana, ana, bo with a window of 2:

Window of 2A setA Counter
ana, ana{ana}{ana: 2}
ana, bo{bo}: 1 key, wrong{ana: 1, bo: 1}: 2 keys, right

A key can be in the window twice, and a set doesn't know that. When the first ana leaves, removing it from the set forgets ana, while the second copy is still inside.

The window needs a count per key: a Counter. Add 1 for the key that enters, and take 1 off the key that leaves. Then len(counts) is the number of different keys, with one catch:

from collections import Counter

c = Counter(["ana", "bo", "ana"])
c["bo"] -= 1
print(c, len(c), "bo" in c)
Counter({'ana': 2, 'bo': 0}) 2 True

bo has left the window and is still a key. A count of 0 doesn't remove it. Delete a key when its count reaches 0, or len(counts) counts clients that are gone:

from collections import Counter

c = Counter(["ana", "bo", "ana"])
c["bo"] -= 1
if c["bo"] == 0:
    del c["bo"]
print(c, len(c))
Counter({'ana': 2}) 1

The editor holds distinct_per_window, with the first window already counted in a Counter. Write the updates inside the loop: the key that enters and the key that leaves.