10/32
Part 3 of 6 · A growing windowLearn and do
Left only moves forward, so the inner loop runs at most n times in all
A while inside a for looks like O(n²). Here it isn't. Count what happened to each entry in the trace above:
| Index | Key | Added at | Dropped at |
|---|---|---|---|
| 0 | u3 | 0 | 2 |
| 1 | u7 | 1 | 5 |
| 2 | u3 | 2 | 7 |
| 3 | u1 | 3 | 7 |
| 4 to 7 | u9, u7, u2, u1 | 4 to 7 | never |
| in all | 8 adds | 4 drops |
Each entry is added once, when right reaches it. It's dropped at most once, when left passes it, because left never moves back. So the inner loop runs at most n times over the whole pass, not n times per step. On a million random keys drawn from 1,000 clients, it removed 999,939 entries in total.
The whole pass is O(n) time, with memory for the keys in the window. Here it is on logs where every key is different, the worst case for starting over:
| n | Every start | Window with a set | Window with last positions |
|---|---|---|---|
| 1,000 | 13.2 ms | 0.111 ms | 0.111 ms |
| 2,000 | 53.4 ms | 0.229 ms | 0.234 ms |
| 4,000 | 213.8 ms | 0.455 ms | 0.463 ms |
Write drops: your loop from windows, with a counter in its while loop, so you see how many entries it removes over a whole pass.