MediumStateful DesignPython 3

TTL Key/Value Store

Build a deterministic in-memory store where every read path treats expired keys as missing.

35m1 sample tests1 hidden tests

TTL Key/Value Store

Implement an in-memory Store with set, get, delete, and scan.

Requirements

  • Store(now) receives a zero-argument clock function.
  • set(key, value, ttl=None) stores a value. ttl is measured in seconds.
  • get(key) returns the value or None when missing or expired.
  • delete(key) removes a key and returns True if it existed and was not expired.
  • scan(prefix) returns sorted (key, value) pairs for non-expired keys whose key starts with prefix.
  • Expiry is inclusive: a key is expired when now() >= expires_at.

Example

python
1clock = {"t": 0} 2store = Store(lambda: clock["t"]) 3store.set("user:1", "Ada", ttl=10) 4assert store.get("user:1") == "Ada" 5clock["t"] = 10 6assert store.get("user:1") is None

Constraints

  • Do not use sleep in tests or implementation.
  • Use standard-library Python only.

Editor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Sample Tests
expires keys at the boundary
from solution import Store

clock = {"t": 0.0}
store = Store(lambda: clock["t"])
store.set("user:1", "Ada", ttl=10)
assert store.get("user:1") == "Ada"
clock["t"] = 9.999
assert store.get("user:1") == "Ada"
clock["t"] = 10.0
assert store.get("user:1") is None
Results
Run sample tests or submit all tests.