KatInterview

Rolling-Window Key-Value Store with Live Average

Data Structure DesignModel answer
MediumModel answerData Structure Designhash-maplinked-listsliding-window

Last updated

Design a key-value store that expires entries older than a configurable time window and supports O(1) average-case get, put, and average queries.

Rolling-Window Key-Value Store with Live Average

You are building a lightweight in-memory store for a metrics pipeline. The store accepts numeric readings tagged by a string key. Each reading is only meaningful for a fixed duration: once a reading is older than window_ms milliseconds it is considered stale and must never be surfaced to callers.

Implement the class RollingStore with these three methods:

put(key, value) Record value for key, timestamped at the current time. If key already exists (expired or not), this call replaces it entirely and resets its timestamp to now.

get(key) -> float | None Return the stored value for key if it exists and is not stale. Return None if the key is absent or has expired. This call must not change the key's timestamp.

average() -> float | None Return the mean of every value that is currently within the window. If no values are live, return None (do not return 0 and do not raise a division error).

Rules and constraints

  • An entry with timestamp ts is valid when ts >= now - window_ms. An entry exactly window_ms old is still valid; the boundary is inclusive on the older end.
  • You can assume that all currently valid entries fit in memory at any one time, but the full history of all writes does not. Your implementation must free expired data.
  • The system is single-threaded; no concurrency concerns.
  • Inject the clock as a callable so that tests can control time without sleeping.
  • window_ms must be a positive integer; reject 0 or negative values.

What you are expected to produce

  1. The implementation in your language of choice.
  2. A discussion of the data structures you chose and why.
  3. Time and space complexity for each method, including the amortized argument.
  4. At least two design trade-offs or edge cases you considered.

Example

store = RollingStore(window_ms=10_000, clock=mock_clock)

mock_clock.set(t=0)
store.put("cpu", 40)
store.put("mem", 80)
store.average()        # → 60.0

mock_clock.set(t=5_000)
store.put("cpu", 50)   # refreshes "cpu" timestamp to t=5000
store.average()        # → 65.0  (both keys still valid)

mock_clock.set(t=10_001)
# "mem" was inserted at t=0; now - window_ms = 10_001 - 10_000 = 1 → ts 0 < 1, expired
store.get("mem")       # → None
store.average()        # → 50.0  (only "cpu" at t=5000 survives)

mock_clock.set(t=20_000)
store.average()        # → None  (all entries expired)

Hints

Hint 1

Think about what ordering property put() gives you for free: since every new timestamp equals 'now' and the clock never goes backward, insertion order and timestamp order are always the same. Does that suggest a simpler sort strategy than a heap?

Hint 2

You need O(1) lookup by key and O(1) removal of the oldest entries. Two separate data structures, each good at one of those things, can be linked together — this is the same pairing used in an LRU cache.

Hint 3

Rather than scanning all entries on every average() call, maintain a running sum and update it incrementally on every put and every eviction. What bookkeeping lets you keep that sum exact when a key is overwritten before it expires?