progress

~/problems / Streams & durability / Rolling windows and rate counters

Café drink counts over the last N seconds

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A café's till shows two live numbers: how many of a given drink were ordered recently, and how many different drinks were.

Build DrinkCounter(window):

  • order(t, drink) -> None: one order of drink at integer second t.
  • count(t, drink) -> int: orders of drink in the window ending at t.
  • variety(t) -> int: distinct drinks with at least one order in that window.

The window ending at t holds orders with t - window < time <= t. t never decreases across all calls, and many orders can share a second.

c = DrinkCounter(60)
c.order(0, "latte")
c.order(10, "mocha")
c.order(30, "latte")
c.count(30, "latte")    # 2
c.variety(30)           # 2
c.count(60, "latte")    # 1   (the order at 0 is 60 seconds old: gone)
c.variety(75)           # 1   (only the latte at 30 is left)
c.count(75, "tea")      # 0
c.variety(90)           # 0

⭐ Bonus: rescanning the history still passes; a speed test with hundreds of thousands of calls earns a star if every call is O(1) amortized, meaning O(1) on average over many calls (no looping over all drinks in variety).

Show hint

a deque of (t, drink) plus a dict drink -> count for the window. Before each call, pop expired orders and decrement, deleting drinks that reach 0; variety is len(dict).

Topic: Rolling windows and rate counters. QPS over the last N seconds, hit counters, rate limiters.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc