Sliding-Window Expiring Key-Value Map
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement a single-threaded in-memory WindowedMap that maps hashable keys to numeric values (int or float) and exposes only entries written within a trailing time window of length window_ms milliseconds.
Timestamps come from a non-decreasing integer millisecond clock (clock). An entry written at timestamp t is valid while now - t <= window_ms and expired as soon as now - t > window_ms. Expired entries must never appear in reads or averages. All currently valid entries at any instant fit comfortably in RAM, whereas the cumulative stream of historical entries over the program's lifetime does not, so expired entries must be evicted rather than kept indefinitely.
Implement WindowedMap with the following methods, aiming for O(1) expected or amortized time per operation:
__init__(window_ms: int, clock: Optional[Callable[[], int]] = None) -> None: Creates an empty windowed store. RaisesValueErrorifwindow_ms <= 0. WhenclockisNone, uses a default monotonic millisecond clock.get(key: Hashable) -> Optional[float]: Returns the value currently mapped tokeyifkeyis present and not expired atclock(), orNoneotherwise. Callinggetdoes not refreshkey's timestamp.put(key: Hashable, value: float) -> None: Insertskeywithvalue(or replaceskey's previous value) and stampskeywith the current timestampclock().get_average() -> Optional[float]: Returns the arithmetic mean (float) across all currently non-expired keys atclock(), orNonewhen zero valid keys exist.
Examples
Example 1
# Using an injected test clock starting at t = 100 ms with window_ms = 500
store = WindowedMap(500, clock=clock)
clock.now = 100
store.put("cpu", 40)
clock.now = 250
store.put("mem", 70)
store.get_average() # -> 55.0
clock.now = 600
store.get("cpu") # -> 40 (600 - 100 == 500 <= 500; get does not extend lifetime)
clock.now = 601
store.get("cpu") # -> None (601 - 100 == 501 > 500)
store.get_average() # -> 70.0 (only "mem" remains valid)
clock.now = 800
store.get_average() # -> None (both keys have expired)
Explanation: At t = 250, both "cpu" (40) and "mem" (70) are inside the 500 ms window, giving mean 55.0. At t = 600, "cpu" is right on the inclusive boundary (age == 500) and still returns 40, without refreshing its write timestamp. One millisecond later (t = 601), "cpu" expires, leaving "mem" alone with mean 70.0; by t = 800, "mem" has also expired and get_average() returns None.
Example 2
store = WindowedMap(50, clock=clock)
clock.now = 0
store.put("k1", 12)
clock.now = 20
store.put("k2", 18)
clock.now = 40
store.put("k1", 42) # overwrites 12 -> 42 and updates "k1"'s timestamp to 40
clock.now = 45
store.get("k1") # -> 42
store.get_average() # -> 30.0 ((18 + 42) / 2)
clock.now = 75
store.get("k2") # -> None (75 - 20 == 55 > 50)
store.get("k1") # -> 42 (75 - 40 == 35 <= 50)
store.get_average() # -> 42.0
Explanation: Re-inserting "k1" at t = 40 replaces its old value (12 -> 42) in the active sum and resets its expiration window to [40, 90], so "k1" outlives "k2" when the clock advances to t = 75.
Constraints
window_msis a positive integer (window_ms <= 0raisesValueError).clock()returns non-decreasing integer milliseconds.keycan be any hashable Python object;valueis anintorfloat(including0and negative numbers).- Single-threaded execution only.
- Memory usage must scale with the active window size rather than the total number of historical
putcalls.
Step-by-step walkthrough
Pin down the window rules and API contract
We want an in-memory map from
keyto a numericvaluewhere everyput(key, value)stamps that key with the current millisecond timestampnow, and entries written outside the trailingwindow_mswindow vanish from both lookups and averages.Before selecting data structures, settle every boundary rule:
- Inclusive window boundary: An entry written at timestamp
tremains live whilenow - t <= window_msand expires oncenow - t > window_ms. Withwindow_ms = 500, a write att = 100is still valid att = 600(600 - 100 == 500) and expired att = 601. - Missing or expired keys:
get(key)returnsNone, and reading never extends a key's lifetime. Because0and negative numbers are valid stored values, callers checkresult is Nonerather than truthiness. - Empty window average:
get_average()returnsNonewhen zero live keys exist, avoiding division by zero. - Injected monotonic clock: Accept an optional zero-argument
clockcallable returning integer milliseconds so tests can control time deterministically without sleeping. Default to a monotonic clock — a system timer guaranteed never to step backward even when NTP adjusts the machine's wall clock.
from typing import Callable, Hashable, Optional class WindowedMap: def __init__(self, window_ms: int, clock: Optional[Callable[[], int]] = None) -> None: ... def get(self, key: Hashable) -> Optional[float]: ... def put(self, key: Hashable, value: float) -> None: ... def get_average(self) -> Optional[float]: ...- Inclusive window boundary: An entry written at timestamp
Why a plain dictionary is too slow and leaks memory
The first-pass brute-force idea stores
self._data[key] = (value, timestamp)inside a regular dictionary: -get(key)looks upkeyand checksnow - timestamp <= window_msinO(1)time. -get_average()scans every key ever inserted, averaging those withnow - timestamp <= window_ms.That approach breaks down on two requirements: 1. Memory leak over lifetime traffic: Expired keys stay in the dictionary forever, eventually exhausting RAM when historical traffic outgrows memory. 2. Linear-time averages: Even if expired entries were purged periodically, summing
100,000active entries on everyget_average()call costsO(n)instead ofO(1).We need a structure that evicts expired entries in chronological order without scanning active items, paired with a running sum of active values.
Key insight: last-put order equals expiry order
Because every key shares the exact same
window_msduration and our monotonic clock never moves backward, sorting keys by their latestputtimestamp automatically sorts them by expiration time. The oldestputat the front is guaranteed to expire before every entry behind it!That means our container needs three
O(1)operations: -O(1)lookup bykey(forget), -O(1)peek and pop from the oldest front (to evict expired entries), -O(1)unlink from the middle and re-append at the newest back (whenputoverwrites an existing key).Pairing a hash map with a doubly linked list (a chain of nodes holding
prevandnextpointers so any node unlinks inO(1)time) provides all three. Python'scollections.OrderedDictimplements this exact structure:OrderedDict queue with window_ms = 50 (oldest at front ---> newest at back): 1) put("k1", 12) at t=0, put("k2", 18) at t=20: front -> [ "k1": (12, t=0) ] <-> [ "k2": (18, t=20) ] <- back _sum = 30 2) put("k1", 42) at t=40 (pop "k1" from front, re-append at back!): front -> [ "k2": (18, t=20) ] <-> [ "k1": (42, t=40) ] <- back _sum = 60 3) Evict at t=75 with window_ms=50: - inspect front "k2": 75 - 20 = 55 > 50 (expired!) -> delete "k2", _sum = 42 - inspect front "k1": 75 - 40 = 35 <= 50 (valid!) -> STOP immediatelyWatch out for the subtle trap on step 2: assigning
entries["k1"] = (42, 40)in place leaves"k1"at its old front slot, stranding"k2"behind"k1"past"k2"'s expiration! Popping"k1"before inserting moves"k1"to the newest tail.Build the state and lazy front-eviction helper
Rather than running background sweeper threads (which complicate single-threaded state with locks), we use lazy eviction: expired nodes sit harmlessly at the front until
putorget_averagepops them.Inside
_evict_expired(now),next(iter(self._entries))reads the doubly linked list head inO(1)time. As soon as the head entry is still valid, every entry behind it has an equal or newer timestamp and must also be valid, so the loop terminates immediately.from typing import Callable, Dict, Hashable, Optional, Tuple from collections import OrderedDict import time def _monotonic_ms() -> int: """Default clock: integer milliseconds from a monotonic clock that never jumps backwards.""" return time.monotonic_ns() // 1_000_000 class WindowedMap: def __init__(self, window_ms: int, clock: Optional[Callable[[], int]] = None) -> None: if window_ms <= 0: raise ValueError("window_ms must be positive") self._window_ms = window_ms self._clock = clock if clock is not None else _monotonic_ms # _entries: OrderedDict mapping key -> (value, timestamp_ms), e.g. {"cpu": (40, 100), "mem": (70, 250)}. # OrderedDict pairs a hash map with a doubly linked list in last-put order, which matches # expiry order from oldest (front) to newest (back) because the clock never goes backwards. self._entries: "OrderedDict[Hashable, Tuple[float, int]]" = OrderedDict() # _sum: running total of all values currently present in self._entries self._sum = 0 def _is_expired(self, timestamp: int, now: int) -> bool: # Strict '>': an entry at age == window_ms is still inside the most recent window return now - timestamp > self._window_ms def _evict_expired(self, now: int) -> None: """Pop expired entries from the oldest (front) end until a valid entry is reached.""" while self._entries: # Peek at the oldest entry in O(1) via the doubly linked list head oldest_key = next(iter(self._entries)) value, timestamp = self._entries[oldest_key] if not self._is_expired(timestamp, now): # Every entry behind oldest_key has timestamp >= oldest timestamp, so none are expired break del self._entries[oldest_key] self._sum -= valueImplement get, put, and get_average
All three operations maintain one clean invariant:
self._sumalways equals the sum of values currently stored inself._entries.get(key)looks upkeyinself._entriesand checks_is_expired. Skipping_evict_expiredinsidegetkeeps every lookup strictlyO(1)expected time even right after a quiet interval, and read-only calls never allocate new entries.put(key, value)runs three phases:- Call
_evict_expired(now)so any expired nodes (including a stale copy ofkeyitself) are removed and subtracted fromself._sum. - Call
self._entries.pop(key, None). Ifkeywas still live,popunlinks its old node and we subtractold_valuefromself._sum; ifkeyalready expired in phase 1,popreturnsNoneso we never double-subtract. - Insert
self._entries[key] = (value, now)at the back and addvaluetoself._sum.
- Call
get_average()runs_evict_expired(now)soself._entriesandself._sumreflect only live keys, then returnsself._sum / len(self._entries)(orNonewhen empty).
def get(self, key: Hashable) -> Optional[float]: # O(1) hash lookup without modifying timestamps or doing eviction work entry = self._entries.get(key) if entry is None: return None value, timestamp = entry now = self._clock() if self._is_expired(timestamp, now): return None return value def put(self, key: Hashable, value: float) -> None: now = self._clock() # Phase 1: evict expired entries first so memory stays bounded by active window size self._evict_expired(now) # Phase 2: remove any existing still-valid entry for `key` and subtract its old value. # Overwriting self._entries[key] in place would keep its old queue position and break sort order! old_entry = self._entries.pop(key, None) if old_entry is not None: old_value, _ = old_entry self._sum -= old_value # Phase 3: insert at the newest (back) end with timestamp `now` and add the new value self._entries[key] = (value, now) self._sum += value def get_average(self) -> Optional[float]: now = self._clock() # Evict expired entries so self._sum and len(self._entries) count only currently valid keys self._evict_expired(now) if not self._entries: return None return self._sum / len(self._entries)Trace Example 1 and analyze O(1) bounds
Walk through Example 1 (
window_ms = 500):Time Call OrderedDict (oldest -> newest) _sum Return ----- ------------------- ---------------------------------------- ---- ------ t=100 put("cpu", 40) [("cpu", 40, 100)] 40 None t=250 put("mem", 70) [("cpu", 40, 100), ("mem", 70, 250)] 110 None t=250 get_average() 0 evicted -> 110 / 2 110 55.0 t=600 get("cpu") 600 - 100 == 500 <= 500 (still valid) 110 40 t=601 get("cpu") 601 - 100 == 501 > 500 (expired) 110 None t=601 get_average() evicts "cpu" (_sum=70); "mem" valid -> 70/1 70 70.0 t=800 get_average() evicts "mem" (_sum=0); empty -> None 0 NoneWhat complexity bounds are and are not achieved? -
getis O(1) expected time per call: One hash lookup and one integer subtraction, with no eviction loop. -putandget_averageare O(1) amortized expected time: Amortized O(1) means the average work per call across any sequence ofMoperations is bounded by a constant, even if an individual call cleans up multiple expired keys. Because everyputinserts at most one node and each node is deleted at most once,Moperations perform at mostMtotal deletions. - Why strict single-call worst-case O(1) is not achieved: After100,000writes followed by a quiet pause longer thanwindow_ms, the nextputorget_averagepops all100,000expired nodes in oneO(n)sweep.Full solution
Putting the monotonic clock helper and
WindowedMaptogether produces the complete implementation.from typing import Callable, Dict, Hashable, Optional, Tuple from collections import OrderedDict import time def _monotonic_ms() -> int: """Default clock: integer milliseconds from a monotonic clock that never jumps backwards.""" return time.monotonic_ns() // 1_000_000 class WindowedMap: """Key -> numeric value store that only keeps puts from the last window_ms. An entry written at time t is valid while now - t <= window_ms and expired once now - t > window_ms. The clock returns integer milliseconds and must never go backwards; tests pass a fake clock. """ def __init__(self, window_ms: int, clock: Optional[Callable[[], int]] = None) -> None: if window_ms <= 0: raise ValueError("window_ms must be positive") self._window_ms = window_ms self._clock = clock if clock is not None else _monotonic_ms # _entries: OrderedDict mapping key -> (value, timestamp_ms), e.g. {"cpu": (40, 100), "mem": (70, 250)}. # OrderedDict pairs a hash map with a doubly linked list in last-put order, which matches # expiry order from oldest (front) to newest (back) because the clock never goes backwards. self._entries: "OrderedDict[Hashable, Tuple[float, int]]" = OrderedDict() # _sum: running total of all values currently present in self._entries self._sum = 0 def _is_expired(self, timestamp: int, now: int) -> bool: # Strict '>': an entry at age == window_ms is still inside the most recent window return now - timestamp > self._window_ms def _evict_expired(self, now: int) -> None: """Pop expired entries from the oldest (front) end until a valid entry is reached.""" while self._entries: # Peek at the oldest entry in O(1) via the doubly linked list head oldest_key = next(iter(self._entries)) value, timestamp = self._entries[oldest_key] if not self._is_expired(timestamp, now): # Every entry behind oldest_key has timestamp >= oldest timestamp, so none are expired break del self._entries[oldest_key] self._sum -= value def get(self, key: Hashable) -> Optional[float]: # O(1) hash lookup without modifying timestamps or doing eviction work entry = self._entries.get(key) if entry is None: return None value, timestamp = entry now = self._clock() if self._is_expired(timestamp, now): return None return value def put(self, key: Hashable, value: float) -> None: now = self._clock() # Phase 1: evict expired entries first so memory stays bounded by active window size self._evict_expired(now) # Phase 2: remove any existing still-valid entry for `key` and subtract its old value. # Overwriting self._entries[key] in place would keep its old queue position and break sort order! old_entry = self._entries.pop(key, None) if old_entry is not None: old_value, _ = old_entry self._sum -= old_value # Phase 3: insert at the newest (back) end with timestamp `now` and add the new value self._entries[key] = (value, now) self._sum += value def get_average(self) -> Optional[float]: now = self._clock() # Evict expired entries so self._sum and len(self._entries) count only currently valid keys self._evict_expired(now) if not self._entries: return None return self._sum / len(self._entries)✅ Submit now — all tests should pass.
Intuition & how it works
Picture a moving conveyor belt of labeled cards paired with a live digital counter showing the total sum of cards currently riding on the belt. Each put(key, value) places a card at the right (newest) end of the belt — plucking key's older card out of the middle first if one is already riding — and updates the running sum. Because every card expires after the exact same window_ms duration and our clock never moves backward, cards always go stale at the left (oldest) edge first, so we simply drop expired cards off the left edge until we reach a card that is still fresh.
A naive implementation storing key -> (value, timestamp) in a plain dictionary fails on both memory and speed. Without eviction, historical keys pile up indefinitely and exhaust memory; and if get_average() loops across all n live keys to add them up on every call, each average query costs O(n) instead of O(1).
Trace Example 2 with window_ms = 50:
1. At t = 0, put("k1", 12) appends "k1": (12, 0) to an OrderedDict (a hash map backed by a doubly linked list, where each node points to its neighbors so unlinking from any position takes O(1) time); _sum becomes 12.
2. At t = 20, put("k2", 18) appends "k2": (18, 20); the queue from oldest to newest is ["k1", "k2"] and _sum is 30.
3. At t = 40, put("k1", 42) pops "k1" (_sum drops to 18) and appends "k1": (42, 40) at the back; the queue becomes ["k2", "k1"] and _sum becomes 60, so get_average() at t = 45 immediately returns 60 / 2 = 30.0.
4. At t = 75, get_average() runs lazy eviction (purging stale front entries during normal calls rather than via background threads): it inspects front key "k2" (75 - 20 = 55 > 50), deletes "k2" (_sum drops to 42), sees "k1" is valid (75 - 40 = 35 <= 50), stops immediately, and returns 42 / 1 = 42.0.
Complexity
get(key)— O(1) expected time per call: Executes one hash lookup inself._entriesand one subtractionnow - timestamp > self._window_ms, without running the eviction loop.put(key, value)— O(1) amortized expected time: Amortized time measures the average cost per operation across any worst-case sequence ofMcalls, charging occasional multi-item eviction sweeps back to the earlierputcalls that inserted those items. Unlinking an existingkeyand appending(value, now)each takeO(1)hash and pointer updates, and every inserted entry can be evicted at most once across the entire run.get_average()— O(1) amortized expected time (O(n) single-call worst case): After_evict_expiredpops any newly expired front nodes,self._sum / len(self._entries)is a singleO(1)division. Following an idle pause longer thanwindow_ms, the first call sweeps up tonexpired keys at once (O(n)), already paid for by theirninsertions.- Space — O(V): Right after any
put,self._entriescontains only theVcurrently valid keys.getnever allocates entries andget_averageonly removes expired ones, so memory stays bounded by the peak active window sizemax(V)regardless of lifetime write volume. (UsingOrderedDictrather than a plaindictalso avoids scanning internal tombstone slots — empty deletion markers left at the front of CPython's dict array until a resize — keepingnext(iter(self._entries))strictlyO(1).)
Edge cases
- Exact window boundary: With
window_ms = 500, a write att = 100is valid att = 600(600 - 100 <= 500) and expired att = 601(601 - 100 > 500). Sharing_is_expiredacrossgetand_evict_expiredkeeps both paths consistent. - Overwriting an active key:
putremoves the existing node, subtractsold_value, appends the updated node at the newest tail, and addsvalue. - Re-inserting an already-expired key: Phase 1 (
_evict_expired) deletes the expired entry and subtracts its value once, so phase 2 (pop(key, None)) returnsNoneand avoids subtracting twice. - Zero and negative values:
0and negative numbers are valid stored values;getreturns0rather thanNone. - Empty store or all keys expired:
get_average()checksif not self._entries:after eviction and returnsNoneinstead of raisingZeroDivisionError. - Clock monotonicity: Wall clocks (
time.time()) can jump backward during NTP syncs and break queue ordering; defaulting totime.monotonic_ns()preserves non-decreasing timestamps. - Floating-point rounding drift: Repeatedly adding and subtracting wildly different
floatmagnitudes can accumulate rounding error ((0.0 + 1e16 + 1.0) - 1e16 == 0.0). Fixed-point integers stay exact, or Neumaier's compensated summation (tracking lost low-order bits in a separate error term) keepsO(1)updates accurate across arbitrary floats.
Common mistakes
- Assigning
self._entries[key] = (value, now)in place: Updating an existing key insideOrderedDict(or Java'sLinkedHashMap) leaves the key at its old queue position unless you pop/re-insert (or callmove_to_end), breaking chronological eviction order. - Forgetting to subtract
old_valuewhen overwriting a live key: Leaveslen(self._entries)unchanged while inflatingself._sumbyold_value. - Filtering expired keys on read without deleting them: Passes small correctness tests while leaking memory linearly with lifetime traffic.
- Summing
self._entriesinsideget_average(): Degradesget_average()fromO(1)amortized toO(n)on every call. - Checking
if not store.get(k):instead ofif store.get(k) is None:: Misinterprets a valid0value as missing. - Claiming strict single-call worst-case
O(1): Lazy eviction guaranteesO(1)amortized, not worst-case per call after an idle gap.
Alternative approaches
- Min-heap of
(expire_at, key)with lazy deletion: Needed when each write specifies a custom TTL, atO(log n)perputinstead ofO(1)amortized. - Fixed-size millisecond ring buffer: Pre-allocate
window_ms + 1buckets storing(timestamp, sum, count)whenwindow_msis small, bounding bucket advancement toO(min(elapsed, window_ms)), while still pairing with hash-map eviction to bound key memory. - Evicting inside
getas well: Reclaims memory during read-only periods at the cost of makinggetO(1)amortized instead ofO(1)expected per call.
Follow-up questions
- How would you synchronize WindowedMap so concurrent reader and writer threads never corrupt the expiry order? Guard
get,put, andget_averagewith a singlethreading.Lock, and crucially readself._clock()inside that lock rather than before acquiring it. If Thread A samplesnow = 10and Thread B samplesnow = 12, but Thread B enters the critical section first, Thread A would appendt = 10behindt = 12and break front-to-back expiry order! Becausegetin our implementation never mutates_entriesor_sum, a readers-writer lock can also let multiplegetcalls run concurrently whileputandget_averageacquire exclusive access. - What data structures would you need to support get_max() or get_median() across currently valid entries? Unlike a sum, neither a maximum nor a median can recover the next runner-up in
O(1)when the top element is overwritten or evicted. If keys are never overwritten downward, a monotonic deque (a double-ended queue kept in non-increasing value order) answersget_max()inO(1)amortized time; with arbitrary key overwrites, pair_entrieswith a max-heap of(-value, timestamp, key)and lazily pop stale or expired heap tops inO(log n)amortized time. Forget_median(), maintain two balanced heaps (lower-half max-heap and upper-half min-heap) with lazy deletion and explicit live sizes inO(log n)per update. - How would the design change if each put(key, value, ttl_ms) accepted its own custom expiration duration? Once entries have heterogeneous lifetimes, insertion order no longer matches expiration order — a key written early with
ttl_ms = 60_000outlives a key written later withttl_ms = 50. Replace theOrderedDictqueue with a hash mapkey -> (value, expire_at)plus a min-heap of(expire_at, key). Eachputupdates the hash map, adjusts_sumif overwriting a still-live key (old_expire_at >= now), and pushes(now + ttl_ms, key)onto the heap inO(log n);_evict_expiredpops heap entries withexpire_at < now, ignoring stale heap entries whoseexpire_atno longer matchesmap[key].
Follow-up questions
- How would you synchronize WindowedMap so concurrent reader and writer threads never corrupt the expiry order?
- What data structures would you need to support get_max() or get_median() across currently valid entries?
- How would the design change if each put(key, value, ttl_ms) accepted its own custom expiration duration?
Similar questions
- Hash Map Lookup and Key-Extraction Complexity Analysis
- Running Median of an Integer Stream
- Level-Order Tree Reconstruction from Preorder and Inorder
- Two-Flip Fair Coin Conditional Probabilities
- Optimal Desert Banana Transport with Relay Depots
- Hierarchical Recipe and Pantry Fulfillment Service
More StackAdapt interview questions
- Hierarchical Recipe and Pantry Fulfillment Service Easy
- Level-Order Tree Reconstruction from Preorder and Inorder Medium
- Hash Map Lookup and Key-Extraction Complexity Analysis Medium Pro
- Two-Flip Fair Coin Conditional Probabilities Easy Pro
- Optimal Desert Banana Transport with Relay Depots Medium Pro
- Mean vs. Median of the Geometric Distribution Easy Pro
- Auditing Methodological Flaws in an ML Pipeline Report Medium Pro
- Running Median of an Integer Stream Easy Pro
- Single-Pass Uniform k-Item Reservoir Sampling Medium Pro