Two-Level In-Memory Store with Field Expiration

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

Design an in-memory two-tier data store TimestampedDB where every top-level key maps to named field entries, and each field optionally carries an integer time-to-live (ttl). Missing fields and expired fields must behave identically on reads and scans.

Class and Method Signatures

from typing import Any, List, Optional, Tuple


class TimestampedDB:
    def __init__(self) -> None: ...

    def SET(self, key: str, field: str, value: Any, ttl: int, now: int = 0) -> None: ...

    def GET(self, key: str, field: str, now: int) -> Optional[Any]: ...

    def DELETE(self, key: str, field: str) -> None: ...

    def SCAN(self, key: str, now: int) -> List[Tuple[str, Any]]: ...

    def SCAN_PREFIX(self, key: str, field_prefix: str, now: int) -> List[Tuple[str, Any]]: ...

Operation Rules

  1. SET(key, field, value, ttl, now=0):
    • Writes value under (key, field) at integer clock timestamp now (defaulting to 0), replacing any previous value and expiration setting on that field.
    • If ttl > 0, the entry stays live during [now, now + ttl)—meaning it is live while t < now + ttl and expired at every timestamp t >= now + ttl.
    • If ttl == 0, the entry never expires.
    • If ttl < 0, raise ValueError without modifying the store.
  2. GET(key, field, now):
    • Returns the stored value if (key, field) is present and live at timestamp now; otherwise returns None.
  3. DELETE(key, field):
    • Removes (key, field) if present; if key or field does not exist, performs no action.
  4. SCAN(key, now):
    • Returns a list of (field, value) tuples for every live field under key at timestamp now, sorted in ascending lexicographic (Unicode code-point) order by field. Returns [] if key is absent or has no live fields.
  5. SCAN_PREFIX(key, field_prefix, now):
    • Returns a list of (field, value) tuples for every live field under key at timestamp now whose field name begins with field_prefix, sorted in ascending lexicographic order by field. Returns [] when nothing matches.

Examples

Example 1

db = TimestampedDB()
db.SET("acct:42", "token", "xyz9", 60)   # written at default now=0; expires at t=60
db.SET("acct:42", "plan", "pro", 0)      # ttl=0 -> never expires

db.GET("acct:42", "token", 25)           # -> "xyz9"
db.SCAN("acct:42", 25)                   # -> [("plan", "pro"), ("token", "xyz9")]
db.GET("acct:42", "token", 60)           # -> None
db.SCAN("acct:42", 75)                   # -> [("plan", "pro")]

Explanation: At t = 25, both "plan" and "token" are live (25 < 60), and SCAN orders "plan" before "token" alphabetically. At t = 60, "token" reaches 0 + 60 and expires, so GET returns None and later scans emit only "plan".

Example 2

db = TimestampedDB()
db.SET("cfg:web", "db_host", "10.0.0.5", 0, now=10)
db.SET("cfg:web", "db_port", 5432, 20, now=10)       # expires at 10 + 20 = 30
db.SET("cfg:web", "cache_url", "10.0.0.9", 0, now=10)

db.SCAN_PREFIX("cfg:web", "db_", 25)     # -> [("db_host", "10.0.0.5"), ("db_port", 5432)]
db.SCAN_PREFIX("cfg:web", "db_", 30)     # -> [("db_host", "10.0.0.5")]
db.DELETE("cfg:web", "cache_url")
db.SCAN("cfg:web", 30)                   # -> [("db_host", "10.0.0.5")]

Explanation: SCAN_PREFIX inspects only fields starting with "db_". At t = 25 both "db_host" and "db_port" are live; by t = 30, "db_port" has expired (30 >= 30), and deleting "cache_url" leaves "db_host" as the sole live entry under "cfg:web".

Constraints

  • At most 100,000 operations per test run.
  • key and field are non-empty strings; field_prefix is a string (possibly "").
  • now is an integer system timestamp that never decreases across consecutive calls on the same TimestampedDB instance.

Step-by-step walkthrough

  1. Restate the problem and pin down the TTL rules

    We need an in-memory database that stores values under a two-level hierarchy key -> field -> value, where each field can optionally expire after a Time-To-Live (TTL) — a lifespan measured in integer time units. It supports five operations (SET, GET, DELETE, SCAN, and SCAN_PREFIX) for up to 100,000 calls.

    Before coding, clarify three subtle details in the problem statement:

    • Write timestamp on SET. Computing now + ttl requires knowing the write time now, yet callers starting at t = 0 may omit the write timestamp (as in db.SET("acct:42", "token", "xyz9", 60) expiring at t = 60). Adding now: int = 0 with default 0 supports both four-argument calls at t = 0 and writes at later timestamps.
    • Exact expiration boundary. Consistent with "token" expiring at t = 60, an entry written at now with ttl > 0 is live while current time < now + ttl and expired starting at now + ttl (the half-open interval [now, now + ttl)). Setting ttl == 0 means the entry never expires; ttl < 0 raises ValueError.
    • Non-decreasing system clock. Because now represents system time moving forward, once an entry has expired at time t, it remains expired at all future times.
    SET("k", "f", "v", ttl=10, now=5)  -->  expires_at = 15
    
    time:   5    6   ...   13   14 | 15   16   ...
    state:  [------- LIVE --------) [--- EXPIRED ---
    
  2. Why a flat dictionary is too slow for scans

    The simplest design stores one flat dictionary mapping (key, field) -> (value, expires_at). That makes SET, GET, and DELETE O(1), but every SCAN(key, now) must inspect every entry in the entire database just to find the ones belonging to key, and then sort them.

    Suppose 50,000 SET calls create 5,000 keys with 10 fields each, followed by 50,000 SCAN calls. A flat dictionary checks 50,000 * 50,000 = 2.5 * 10^9 entries, timing out easily even though all 50,000 scans output only 500,000 field-value pairs in total.

    What if we nest dictionaries (key -> {field: (value, expires_at)}) and sort fields.keys() on every scan? That isolates keys from each other, but if a single key holds 50,000 fields and SCAN_PREFIX matches only 2 of them, sorting all 50,000 field names on every prefix scan still wastes O(f log f) work per call.

  3. Store a dictionary plus a sorted field list per key

    To make point lookups fast and prefix scans proportional to the matching slice, we give each key a small _Fields container holding two synchronized structures:

    1. cells: a dictionary field -> (value, expires_at) for O(1) average point lookups and updates.
    2. names: a Python list of the exact same field names, kept in lexicographic order (dictionary order comparing characters by Unicode code point, so "plan" < "token" and "B" < "a10" < "a2" < "b").

    Notice that we store the absolute expiration timestamp expires_at = now + ttl (or None when ttl == 0), not the raw ttl. That turns every future expiration check into one simple comparison now < expires_at.

    from typing import Any, Dict, List, Optional, Tuple
    
    
    def _is_live(expires_at: Optional[int], now: int) -> bool:
        """Return True if the entry never expires (None) or has not yet reached expires_at."""
        # Half-open window [write_time, write_time + ttl): live while now < expires_at, expired at now == expires_at
        return expires_at is None or now < expires_at
    
    
    class _Fields:
        """Per-key container keeping O(1) field lookups in sync with sorted field names."""
    
        def __init__(self) -> None:
            # cells: {field_name: (value, expires_at)}, e.g. {"plan": ("pro", None), "token": ("xyz9", 60)}
            self.cells: Dict[str, Tuple[Any, Optional[int]]] = {}
            # names: sorted list of the exact same field names in cells, e.g. ["plan", "token"]
            self.names: List[str] = []
    
  4. Implement SET, GET, and DELETE with lazy expiry

    Every write or cleanup must keep cells and names holding the exact same set of field names:

    • SET: Compute expires_at. If field is not in cells yet, insert it into names in sorted position using bisect.insort. (Skipping insort when field already exists prevents duplicate names on updates!) Then write (value, expires_at) into cells[field], which cleanly replaces any previous value and TTL.
    • GET: Look up (value, expires_at) in cells. If it has expired, remove it on the spot (lazy deletion — cleaning up expired items when a read encounters them rather than running background timers) and return None.
    • DELETE and _remove: Delete from cells, locate the field in names via binary search (bisect_left — halving the sorted search range at each step in O(log f) comparisons) and pop it, and delete key from self._keys once no fields remain so empty keys occupy zero memory.
    from typing import Any, Dict, Optional
    import bisect
    
    
    class TimestampedDB:
        def __init__(self) -> None:
            # _keys: {key: _Fields}, storing only keys that currently hold at least one field
            self._keys: Dict[str, _Fields] = {}
    
        def SET(self, key: str, field: str, value: Any, ttl: int, now: int = 0) -> None:
            if ttl < 0:
                raise ValueError("ttl must be >= 0")
    
            # ttl == 0 means no expiration; ttl > 0 converts to an absolute expiration timestamp
            expires_at: Optional[int] = None
            if ttl > 0:
                expires_at = now + ttl
    
            fields = self._keys.get(key)
            if fields is None:
                fields = _Fields()
                self._keys[key] = fields
    
            # Insert into the sorted list ONLY when the field is new so updates never create duplicate names
            if field not in fields.cells:
                bisect.insort(fields.names, field)
    
            # Overwrite both the value and the expiration timestamp
            fields.cells[field] = (value, expires_at)
    
        def GET(self, key: str, field: str, now: int) -> Optional[Any]:
            fields = self._keys.get(key)
            if fields is None or field not in fields.cells:
                return None
    
            value, expires_at = fields.cells[field]
            if not _is_live(expires_at, now):
                # Lazy deletion: system time never moves backward, so an expired entry stays expired forever
                self._remove(key, field)
                return None
            return value
    
        def DELETE(self, key: str, field: str) -> None:
            fields = self._keys.get(key)
            if fields is not None and field in fields.cells:
                self._remove(key, field)
    
        def _remove(self, key: str, field: str) -> None:
            """Delete one field from both cells and names, dropping the key if it becomes empty."""
            fields = self._keys[key]
            del fields.cells[field]
            index = bisect.bisect_left(fields.names, field)
            fields.names.pop(index)
            if not fields.cells:
                del self._keys[key]
    
  5. Implement SCAN and SCAN_PREFIX with binary search

    • SCAN(key, now): Walk fields.names from left to right. Because names is already sorted, appending live pairs produces a sorted output with zero sorting work! At the same time, delete expired entries from fields.cells and rebuild fields.names from live_names in one linear pass (avoiding both O(f^2) repeated list pops and Python's RuntimeError from deleting dictionary keys while iterating over that dictionary).
    • SCAN_PREFIX(key, field_prefix, now): In sorted order, every string that starts with field_prefix is >= field_prefix, and all such strings sit right next to each other in one contiguous block:
    fields.names:  ["a",  "aa",  "ab",  "abc",  "ac",  "b"]
    index:           0     1      2      3       4      5
                                  ▲              ▲
          bisect_left("ab") = 2 ──┘              └── "ac".startswith("ab") is False: stop!
    

    So bisect_left(fields.names, field_prefix) jumps straight to the start of the matching run in O(log f) steps, and a while loop walks forward only while startswith(field_prefix) holds, collecting live pairs.

    from typing import Any, List, Tuple
    import bisect
    
    
    class TimestampedDB:
        def SCAN(self, key: str, now: int) -> List[Tuple[str, Any]]:
            fields = self._keys.get(key)
            if fields is None:
                return []
    
            result: List[Tuple[str, Any]] = []
            live_names: List[str] = []
    
            # Walk names in sorted order; purge expired entries from cells while keeping live names sorted
            for name in fields.names:
                value, expires_at = fields.cells[name]
                if _is_live(expires_at, now):
                    result.append((name, value))
                    live_names.append(name)
                else:
                    del fields.cells[name]
    
            fields.names = live_names
            if not fields.cells:
                del self._keys[key]
            return result
    
        def SCAN_PREFIX(self, key: str, field_prefix: str, now: int) -> List[Tuple[str, Any]]:
            fields = self._keys.get(key)
            if fields is None:
                return []
    
            result: List[Tuple[str, Any]] = []
            # In lexicographic order, all strings starting with field_prefix form one contiguous slice
            # starting at the first element >= field_prefix
            index = bisect.bisect_left(fields.names, field_prefix)
            while index < len(fields.names) and fields.names[index].startswith(field_prefix):
                name = fields.names[index]
                value, expires_at = fields.cells[name]
                if _is_live(expires_at, now):
                    result.append((name, value))
                index += 1
            return result
    
  6. Trace the samples step by step

    Let's trace Example 1 from the statement step by step:

    1. SET("acct:42", "token", "xyz9", ttl=60, now=0)
       cells = {"token": ("xyz9", 60)}
       names = ["token"]
    
    2. SET("acct:42", "plan", "pro", ttl=0, now=0)
       insort("plan") places "plan" before "token"
       cells = {"token": ("xyz9", 60), "plan": ("pro", None)}
       names = ["plan", "token"]
    
    3. GET("acct:42", "token", now=25)
       25 < 60 -> live -> returns "xyz9"
    
    4. SCAN("acct:42", now=25)
       walks ["plan", "token"]: both live -> returns [("plan", "pro"), ("token", "xyz9")]
    
    5. GET("acct:42", "token", now=60)
       60 < 60 is False -> expired!
       lazily removes "token" from cells and names -> names = ["plan"]
       returns None
    
    6. SCAN("acct:42", now=75)
       walks ["plan"]: live -> returns [("plan", "pro")]
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Tuple
    import bisect
    
    
    def _is_live(expires_at: Optional[int], now: int) -> bool:
        """Return True if the entry never expires (None) or has not yet reached expires_at."""
        # Half-open window [write_time, write_time + ttl): live while now < expires_at, expired at now == expires_at
        return expires_at is None or now < expires_at
    
    
    class _Fields:
        """Per-key container keeping O(1) field lookups in sync with sorted field names."""
    
        def __init__(self) -> None:
            # cells: {field_name: (value, expires_at)}, e.g. {"plan": ("pro", None), "token": ("xyz9", 60)}
            self.cells: Dict[str, Tuple[Any, Optional[int]]] = {}
            # names: sorted list of the exact same field names in cells, e.g. ["plan", "token"]
            self.names: List[str] = []
    
    
    class TimestampedDB:
        """Two-level in-memory key -> field -> value store with optional per-field TTL."""
    
        def __init__(self) -> None:
            # _keys: {key: _Fields}, storing only keys that currently hold at least one field
            self._keys: Dict[str, _Fields] = {}
    
        def SET(self, key: str, field: str, value: Any, ttl: int, now: int = 0) -> None:
            if ttl < 0:
                raise ValueError("ttl must be >= 0")
    
            # ttl == 0 means no expiration; ttl > 0 converts to an absolute expiration timestamp
            expires_at: Optional[int] = None
            if ttl > 0:
                expires_at = now + ttl
    
            fields = self._keys.get(key)
            if fields is None:
                fields = _Fields()
                self._keys[key] = fields
    
            # Insert into the sorted list ONLY when the field is new so updates never create duplicate names
            if field not in fields.cells:
                bisect.insort(fields.names, field)
    
            # Overwrite both the value and the expiration timestamp
            fields.cells[field] = (value, expires_at)
    
        def GET(self, key: str, field: str, now: int) -> Optional[Any]:
            fields = self._keys.get(key)
            if fields is None or field not in fields.cells:
                return None
    
            value, expires_at = fields.cells[field]
            if not _is_live(expires_at, now):
                # Lazy deletion: system time never moves backward, so an expired entry stays expired forever
                self._remove(key, field)
                return None
            return value
    
        def DELETE(self, key: str, field: str) -> None:
            fields = self._keys.get(key)
            if fields is not None and field in fields.cells:
                self._remove(key, field)
    
        def SCAN(self, key: str, now: int) -> List[Tuple[str, Any]]:
            fields = self._keys.get(key)
            if fields is None:
                return []
    
            result: List[Tuple[str, Any]] = []
            live_names: List[str] = []
    
            # Walk names in sorted order; purge expired entries from cells while keeping live names sorted
            for name in fields.names:
                value, expires_at = fields.cells[name]
                if _is_live(expires_at, now):
                    result.append((name, value))
                    live_names.append(name)
                else:
                    del fields.cells[name]
    
            fields.names = live_names
            if not fields.cells:
                del self._keys[key]
            return result
    
        def SCAN_PREFIX(self, key: str, field_prefix: str, now: int) -> List[Tuple[str, Any]]:
            fields = self._keys.get(key)
            if fields is None:
                return []
    
            result: List[Tuple[str, Any]] = []
            # In lexicographic order, all strings starting with field_prefix form one contiguous slice
            # starting at the first element >= field_prefix
            index = bisect.bisect_left(fields.names, field_prefix)
            while index < len(fields.names) and fields.names[index].startswith(field_prefix):
                name = fields.names[index]
                value, expires_at = fields.cells[name]
                if _is_live(expires_at, now):
                    result.append((name, value))
                index += 1
            return result
    
        def _remove(self, key: str, field: str) -> None:
            """Delete one field from both cells and names, dropping the key if it becomes empty."""
            fields = self._keys[key]
            del fields.cells[field]
            index = bisect.bisect_left(fields.names, field)
            fields.names.pop(index)
            if not fields.cells:
                del self._keys[key]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine a filing cabinet where each drawer folder is a key (like "acct:42"). Inside each folder, you keep two things together: index cards for each field stamped with an expiration time so you can grab any single field immediately, plus an alphabetical checklist of field names on the inside cover so you can read off all fields—or jump straight to fields starting with "db_"—without touching any other folder or re-alphabetizing the whole drawer.

A naive store that puts (key, field) pairs into one giant flat dictionary fails because every SCAN(key, now) has to inspect every entry across all keys—turning 50,000 scans over 50,000 entries into 2.5 billion checks. Even if you group fields by key in nested dictionaries, sorting all fields of key from scratch on every SCAN_PREFIX wastes O(f log f) time when a key has 50,000 fields and only 2 match the prefix.

Walk through a small example on key = "acct:42": 1. SET("acct:42", "token", "xyz9", ttl=60, now=0) converts the Time-To-Live (TTL) (how long an entry stays valid) into an absolute expiration timestamp 0 + 60 = 60, stores ("xyz9", 60) in cells["token"], and puts "token" into the sorted list names = ["token"]. 2. SET("acct:42", "plan", "pro", ttl=0, now=0) stores ("pro", None) (None means no expiry) and uses binary search (repeatedly halving the sorted list to find the insertion spot) to keep names = ["plan", "token"] in lexicographic order (dictionary order by character code). 3. At now = 25, SCAN("acct:42", 25) walks ["plan", "token"] in order, sees None for "plan" and 25 < 60 for "token", and returns [("plan", "pro"), ("token", "xyz9")]. 4. At now = 60, GET("acct:42", "token", 60) sees 60 >= 60, removes "token" from both cells and names via lazy deletion (cleaning up expired data when a read touches it), and returns None.

Complexity

Let f be the number of fields currently stored under the target key (live fields plus any expired fields not yet purged), r be the number of stored fields under key that start with field_prefix, and N be the total number of live or unpurged (key, field) pairs across the whole database (treating string lengths as small constants).

  • SET on an existing field: O(1) average time. We do one hash-map lookup for key, check field in fields.cells in O(1), and overwrite fields.cells[field] without touching the sorted list.
  • SET on a new field: O(f) worst-case time. bisect.insort locates the sorted position in O(log f) comparisons and shifts at most f list references by one slot in C memory (fast for up to 100,000 operations; replaceable by a balanced tree for strict O(log f)).
  • GET: O(1) average time on a live hit or miss; O(f) when lazily removing an expired field because popping from fields.names shifts the tail of that key's list.
  • DELETE: O(f) time to binary-search fields.names in O(log f) and shift the remaining list elements on pop.
  • SCAN: O(f) time. We make one linear pass over fields.names, emitting live pairs already in sorted order and rebuilding live_names in place without re-sorting.
  • SCAN_PREFIX: O(log f + r) time. bisect_left jumps to the first field >= field_prefix in O(log f) steps, and the while loop inspects only the r fields that actually start with field_prefix.
  • Space: O(N) total memory. Every stored (key, field) pair appears once in its key's cells dictionary and once in its key's names list, and empty keys are deleted immediately.

Edge cases

  • Accessing or deleting a missing key or field: GET returns None, SCAN and SCAN_PREFIX return [], and DELETE safely does nothing.
  • Exact expiration boundary (now == write_time + ttl): treated as expired (now < expires_at is required to be live), so an entry written at now = 5 with ttl = 10 is live at t = 14 and expired at t = 15.
  • Overwriting an existing field's TTL: SET replaces both value and expires_at, allowing callers to extend a TTL, shorten it, make an expiring field permanent (ttl = 0), or add a TTL to a permanent field, without duplicating the field name in names.
  • All fields under a key expire: SCAN returns [] and removes the empty key from self._keys; subsequent SET calls cleanly recreate it.
  • Prefix boundary cases: field_prefix = "" returns the same result as SCAN; a prefix equal to an exact field name ("ab") includes "ab" itself; a prefix with no matches returns [].
  • ASCII / Unicode code-point sorting: uppercase letters sort before lowercase ("B" < "a10" < "a2" < "b").

Common mistakes

  • Storing relative ttl instead of absolute now + ttl: without recording when the entry expires on the timeline, later reads cannot tell how much time has elapsed.
  • Calling bisect.insort unconditionally on every SET: updating an existing field adds a second copy of its name to fields.names, causing duplicate rows in SCAN and KeyError crashes after DELETE.
  • Mutating fields.cells while iterating over fields.cells: raises RuntimeError: dictionary changed size during iteration in Python; iterating over fields.names while deleting from fields.cells avoids this cleanly.
  • Computing a prefix upper bound with prefix + "\uffff" or chr(ord(prefix[-1]) + 1): breaks on empty prefixes "" or characters above U+FFFF. Walking forward with startswith(field_prefix) from bisect_left(names, field_prefix) is exact for every string.
  • Using lazy deletion when timestamps can move backward: if queries could ask about past points in time (now = 25 after now = 75), physically deleting at 75 would lose historical state. Lazy deletion relies on now being non-decreasing system time.

Alternative approaches

  • Sort on read (nested dictionaries only): keep only key -> {field: (value, expires_at)} and sort matching fields inside SCAN and SCAN_PREFIX. SET and DELETE become O(1) average always, at the cost of O(f + m log m) per scan (m matching fields)—a good trade-off when writes far outnumber scans.
  • Balanced search tree or skip list per key: guarantees O(log f) worst-case inserts and deletes even if one key receives 100,000 new fields in reverse sorted order, at the cost of significantly more code if third-party libraries like sortedcontainers are unavailable.

Follow-up questions

  • How would you scale this store across machines and disk tiers if the dataset grew to billions of keys beyond a single host's RAM? Partition data across a cluster of nodes by key using consistent hashing (mapping keys and servers onto a hash ring so adding or removing a node moves only ~1/M of the keys). Keeping every field of a single key on one shard preserves single-node GET, SCAN, and SCAN_PREFIX without cross-node scatter-gather queries (unless a single "hot" key holds millions of fields and requires sub-sharding by field range). For cold keys that exceed RAM capacity, spill data onto disk using an LSM-tree storage engine (Log-Structured Merge-tree — an engine like RocksDB that writes sequentially to sorted disk files, keeping prefix scans fast) while caching hot keys in memory.
  • Which auxiliary structure lets a background sweeper reclaim expired fields without iterating through every live key? Maintain a min-heap (a binary tree priority queue that always keeps the smallest element at the top in O(log N) time) of (expires_at, key, field) entries pushed whenever SET assigns ttl > 0. A background worker periodically pops entries from the heap while top.expires_at <= now; before deleting (key, field) from the store, it verifies that cells[field] still carries that exact expires_at so stale heap entries from overwritten or deleted fields are harmlessly skipped. Alternatively, Redis-style probabilistic sampling (periodically checking 20 random keys with TTLs and repeating while >25% are expired) avoids extra heap memory altogether.
  • How would you synchronize concurrent reader and writer threads without serializing operations on unrelated keys? Because every method (SET, GET, DELETE, SCAN, SCAN_PREFIX) acts on a single key, use lock striping (splitting self._keys into a fixed number of buckets—such as 256 shards indexed by hash(key) % 256—each guarded by its own threading.Lock) so threads operating on different keys proceed concurrently without unbounded per-key lock memory. Because GET and SCAN perform lazy deletions, they mutate state and must acquire the shard's exclusive lock (or, under a readers-writer lock, skip physical removal during read-locked queries and defer cleanup to writes and a background sweeper). Always return a freshly allocated list from SCAN and SCAN_PREFIX before releasing the lock so callers never iterate over shared internal lists.

Follow-up questions

Similar questions

More Tradedesk interview questions

All 5 Tradedesk questions →