~/problems / Locks / Lock (mutex)

Thread-safe per-key call counter

medium 3 levels ~40 min Citadel

Level 1 Count calls per key

Write CallCounter() with:

  • count(key) -> int: record one more call for key and return how many times key has been counted so far, including this call (so the first call returns 1).
  • peek(key) -> int: the current count without changing it (0 for a key never counted).

Keys are any hashable values (strings, ints, tuples). Different keys have independent counts.

c = CallCounter()
c.count("a")   # 1
c.count("a")   # 2
c.count("b")   # 1
c.peek("a")    # 2
c.peek("zzz")  # 0

Level 2 unlocks when level 1 passes.

Level 3 unlocks when level 2 passes.

Topic: Lock (mutex). One thread in a critical section at a time.

0:00
Ctrl ' run · Ctrl ↵ submit
esc