Design a time-windowed key-value store
StackAdaptSoftware Engineer · Technical ScreenLast updated
This question evaluates a candidate's ability to design efficient data structures and algorithms for a time-windowed key-value store, focusing on expiration handling, update semantics, and maintaining aggregate metrics under memory constraints.
Implement a time-windowed key-value store ("Windowed Map") that receives key/value updates at irregular times and only keeps entries from the most recent window of length windowMs.
- Each key has a value (assume numeric, e.g.,
doubleorlong) and a timestamp (milliseconds since epoch, e.g., fromSystem.currentTimeMillis()or an injected clock). - Data older than
now - windowMsis expired and must be treated as invisible to the user and eligible for eviction. - You may assume that at any moment, all currently valid entries fit in memory, but the entire lifetime of all entries does not (so you must expire/evict old data).
- Single-threaded only.
Provide these APIs and aim to make them as efficient as possible:
Get(key): ifkeyexists and is not expired, return its value; otherwise returnnull(or throw).
Getdoes not update the timestamp.
Put(key, value): insert or update the key/value.
- Each
Putupdates that key’s timestamp tonow.
GetAverage(): return the average of all currently valid values in the window.
Example:
Put("a", 10)att=0Put("b", 20)att=1GetAverage()returns15.0- After waiting 11 seconds (for a 10-second window):
Get("a")returnsnull(expired)GetAverage()only considers still-valid keys.
Discuss the data structures you would use and the time complexity targets (e.g., O(1) average or worst-case, and what is or isn’t achievable).
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.