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. Raises ValueError if window_ms <= 0. When clock is None, uses a default monotonic millisecond clock.
  • get(key: Hashable) -> Optional[float]: Returns the value currently mapped to key if key is present and not expired at clock(), or None otherwise. Calling get does not refresh key's timestamp.
  • put(key: Hashable, value: float) -> None: Inserts key with value (or replaces key's previous value) and stamps key with the current timestamp clock().
  • get_average() -> Optional[float]: Returns the arithmetic mean (float) across all currently non-expired keys at clock(), or None when 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_ms is a positive integer (window_ms <= 0 raises ValueError).
  • clock() returns non-decreasing integer milliseconds.
  • key can be any hashable Python object; value is an int or float (including 0 and negative numbers).
  • Single-threaded execution only.
  • Memory usage must scale with the active window size rather than the total number of historical put calls.

Step-by-step walkthrough

  1. Pin down the window rules and API contract

    We want an in-memory map from key to a numeric value where every put(key, value) stamps that key with the current millisecond timestamp now, and entries written outside the trailing window_ms window vanish from both lookups and averages.

    Before selecting data structures, settle every boundary rule:

    • Inclusive window boundary: An entry written at timestamp t remains live while now - t <= window_ms and expires once now - t > window_ms. With window_ms = 500, a write at t = 100 is still valid at t = 600 (600 - 100 == 500) and expired at t = 601.
    • Missing or expired keys: get(key) returns None, and reading never extends a key's lifetime. Because 0 and negative numbers are valid stored values, callers check result is None rather than truthiness.
    • Empty window average: get_average() returns None when zero live keys exist, avoiding division by zero.
    • Injected monotonic clock: Accept an optional zero-argument clock callable 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]: ...
    
  2. 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 up key and checks now - timestamp <= window_ms in O(1) time. - get_average() scans every key ever inserted, averaging those with now - 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,000 active entries on every get_average() call costs O(n) instead of O(1).

    We need a structure that evicts expired entries in chronological order without scanning active items, paired with a running sum of active values.

  3. Key insight: last-put order equals expiry order

    Because every key shares the exact same window_ms duration and our monotonic clock never moves backward, sorting keys by their latest put timestamp automatically sorts them by expiration time. The oldest put at the front is guaranteed to expire before every entry behind it!

    That means our container needs three O(1) operations: - O(1) lookup by key (for get), - 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 (when put overwrites an existing key).

    Pairing a hash map with a doubly linked list (a chain of nodes holding prev and next pointers so any node unlinks in O(1) time) provides all three. Python's collections.OrderedDict implements 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 immediately
    

    Watch 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.

  4. 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 put or get_average pops them.

    Inside _evict_expired(now), next(iter(self._entries)) reads the doubly linked list head in O(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 -= value
    
  5. Implement get, put, and get_average

    All three operations maintain one clean invariant: self._sum always equals the sum of values currently stored in self._entries.

    • get(key) looks up key in self._entries and checks _is_expired. Skipping _evict_expired inside get keeps every lookup strictly O(1) expected time even right after a quiet interval, and read-only calls never allocate new entries.
    • put(key, value) runs three phases:
      1. Call _evict_expired(now) so any expired nodes (including a stale copy of key itself) are removed and subtracted from self._sum.
      2. Call self._entries.pop(key, None). If key was still live, pop unlinks its old node and we subtract old_value from self._sum; if key already expired in phase 1, pop returns None so we never double-subtract.
      3. Insert self._entries[key] = (value, now) at the back and add value to self._sum.
    • get_average() runs _evict_expired(now) so self._entries and self._sum reflect only live keys, then returns self._sum / len(self._entries) (or None when 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)
    
  6. 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    None
    

    What complexity bounds are and are not achieved? - get is O(1) expected time per call: One hash lookup and one integer subtraction, with no eviction loop. - put and get_average are O(1) amortized expected time: Amortized O(1) means the average work per call across any sequence of M operations is bounded by a constant, even if an individual call cleans up multiple expired keys. Because every put inserts at most one node and each node is deleted at most once, M operations perform at most M total deletions. - Why strict single-call worst-case O(1) is not achieved: After 100,000 writes followed by a quiet pause longer than window_ms, the next put or get_average pops all 100,000 expired nodes in one O(n) sweep.

  7. Full solution

    Putting the monotonic clock helper and WindowedMap together 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 in self._entries and one subtraction now - 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 of M calls, charging occasional multi-item eviction sweeps back to the earlier put calls that inserted those items. Unlinking an existing key and appending (value, now) each take O(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_expired pops any newly expired front nodes, self._sum / len(self._entries) is a single O(1) division. Following an idle pause longer than window_ms, the first call sweeps up to n expired keys at once (O(n)), already paid for by their n insertions.
  • Space — O(V): Right after any put, self._entries contains only the V currently valid keys. get never allocates entries and get_average only removes expired ones, so memory stays bounded by the peak active window size max(V) regardless of lifetime write volume. (Using OrderedDict rather than a plain dict also avoids scanning internal tombstone slots — empty deletion markers left at the front of CPython's dict array until a resize — keeping next(iter(self._entries)) strictly O(1).)

Edge cases

  • Exact window boundary: With window_ms = 500, a write at t = 100 is valid at t = 600 (600 - 100 <= 500) and expired at t = 601 (601 - 100 > 500). Sharing _is_expired across get and _evict_expired keeps both paths consistent.
  • Overwriting an active key: put removes the existing node, subtracts old_value, appends the updated node at the newest tail, and adds value.
  • 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)) returns None and avoids subtracting twice.
  • Zero and negative values: 0 and negative numbers are valid stored values; get returns 0 rather than None.
  • Empty store or all keys expired: get_average() checks if not self._entries: after eviction and returns None instead of raising ZeroDivisionError.
  • Clock monotonicity: Wall clocks (time.time()) can jump backward during NTP syncs and break queue ordering; defaulting to time.monotonic_ns() preserves non-decreasing timestamps.
  • Floating-point rounding drift: Repeatedly adding and subtracting wildly different float magnitudes 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) keeps O(1) updates accurate across arbitrary floats.

Common mistakes

  • Assigning self._entries[key] = (value, now) in place: Updating an existing key inside OrderedDict (or Java's LinkedHashMap) leaves the key at its old queue position unless you pop/re-insert (or call move_to_end), breaking chronological eviction order.
  • Forgetting to subtract old_value when overwriting a live key: Leaves len(self._entries) unchanged while inflating self._sum by old_value.
  • Filtering expired keys on read without deleting them: Passes small correctness tests while leaking memory linearly with lifetime traffic.
  • Summing self._entries inside get_average(): Degrades get_average() from O(1) amortized to O(n) on every call.
  • Checking if not store.get(k): instead of if store.get(k) is None:: Misinterprets a valid 0 value as missing.
  • Claiming strict single-call worst-case O(1): Lazy eviction guarantees O(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, at O(log n) per put instead of O(1) amortized.
  • Fixed-size millisecond ring buffer: Pre-allocate window_ms + 1 buckets storing (timestamp, sum, count) when window_ms is small, bounding bucket advancement to O(min(elapsed, window_ms)), while still pairing with hash-map eviction to bound key memory.
  • Evicting inside get as well: Reclaims memory during read-only periods at the cost of making get O(1) amortized instead of O(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, and get_average with a single threading.Lock, and crucially read self._clock() inside that lock rather than before acquiring it. If Thread A samples now = 10 and Thread B samples now = 12, but Thread B enters the critical section first, Thread A would append t = 10 behind t = 12 and break front-to-back expiry order! Because get in our implementation never mutates _entries or _sum, a readers-writer lock can also let multiple get calls run concurrently while put and get_average acquire 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) answers get_max() in O(1) amortized time; with arbitrary key overwrites, pair _entries with a max-heap of (-value, timestamp, key) and lazily pop stale or expired heap tops in O(log n) amortized time. For get_median(), maintain two balanced heaps (lower-half max-heap and upper-half min-heap) with lazy deletion and explicit live sizes in O(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_000 outlives a key written later with ttl_ms = 50. Replace the OrderedDict queue with a hash map key -> (value, expire_at) plus a min-heap of (expire_at, key). Each put updates the hash map, adjusts _sum if overwriting a still-live key (old_expire_at >= now), and pushes (now + ttl_ms, key) onto the heap in O(log n); _evict_expired pops heap entries with expire_at < now, ignoring stale heap entries whose expire_at no longer matches map[key].

Follow-up questions

Similar questions

More StackAdapt interview questions

All 10 StackAdapt questions →