Key-Value Store with Prefix Scans, Expirations, and Snapshots

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

Implement an in-memory string key-value store that supports point reads and writes, sorted prefix queries, half-open time-to-live (TTL) expirations, and point-in-time snapshots.

Write the command runner:

def in_memory_database(operations: List[str], arguments: List[List]) -> List:

operations and arguments have equal length and execute sequentially against a single database instance across non-decreasing integer timestamps t. Collect and return one result per command according to these specifications:

  • "put" with [key, value, t] or [key, value, t, ttl]:
    • Stores string value under string key at integer timestamp t, and appends None to the output list.
    • If ttl is omitted, the record never expires.
    • If integer ttl is supplied, the record stays live strictly over the half-open time window [t, t + ttl): reads at timestamp q see it while q < t + ttl, and it is expired as soon as q >= t + ttl (so ttl == 0 expires immediately at t).
    • Calling "put" on an existing key replaces both its value and its expiration rule (for example, overwriting a expiring key without ttl makes it permanent).
  • "get" with [key, t]:
    • Appends the current string value stored at key if key exists and is still live at timestamp t, or None if missing or expired.
  • "scan" with [prefix, t]:
    • Appends a list of [key, value] pairs for every live record at timestamp t whose key begins with prefix (including exact matches key == prefix and empty prefix == ""), sorted in ascending lexicographical order by key.
  • "backup" with [t]:
    • Saves a snapshot of every record that is still live at timestamp t (excluding records already expired by t).
    • Assigns sequential 0-based integer IDs (0, 1, 2, ...) to backups in creation order and appends the newly created backup_id.
    • For each live expiring record, the snapshot records its remaining lifetime (expire_at - t) rather than resetting to its full initial ttl.
  • "restore" with [backup_id, t]:
    • Replaces the entire live database state with the snapshot identified by backup_id (while keeping all stored backups available for future restores) and appends None.
    • Permanent records in that snapshot stay permanent; records saved with remaining_ttl units left resume counting down from t and stay live on [t, t + remaining_ttl).

Examples

Example 1

  • Input:
    • operations = ["put", "get", "put", "get", "get"]
    • arguments = [["cfg:mode", "dev", 2], ["cfg:mode", 3], ["cfg:mode", "prod", 5, 4], ["cfg:mode", 8], ["cfg:mode", 9]]
  • Output: [None, "dev", None, "prod", None]
  • Explanation: "cfg:mode" is first written permanently as "dev" and read at t = 3. At t = 5, it is overwritten with "prod" and ttl = 4, making it valid on [5, 9): get returns "prod" at t = 8 and None once t = 9 reaches the expiration boundary.

Example 2

  • Input:
    • operations = ["put", "put", "put", "put", "scan", "scan"]
    • arguments = [["item:20", "pen", 1], ["item:05", "notebook", 2, 6], ["item:1", "clip", 3], ["other:1", "mug", 4], ["item:", 7], ["item:", 8]]
  • Output: [None, None, None, None, [["item:05", "notebook"], ["item:1", "clip"], ["item:20", "pen"]], [["item:1", "clip"], ["item:20", "pen"]]]
  • Explanation: At t = 7, three keys matching "item:" are live ("item:05" is valid on [2, 8)), and lexicographical order places "item:05" before "item:1" and "item:20". By t = 8, "item:05" has expired and drops out of the scan.

Example 3

  • Input:
    • operations = ["put", "put", "backup", "put", "restore", "scan", "get"]
    • arguments = [["sess:9", "ok", 4, 10], ["sess:1", "perm", 5], [8], ["sess:9", "tampered", 9], [0, 30], ["sess:", 35], ["sess:9", 36]]
  • Output: [None, None, 0, None, None, [["sess:1", "perm"], ["sess:9", "ok"]], None]
  • Explanation: "sess:9" starts valid on [4, 14). When backup(8) creates snapshot 0, "sess:9" has 14 - 8 = 6 time units remaining and "sess:1" is permanent. Restoring snapshot 0 at t = 30 discards "tampered" and makes "sess:9" valid on [30, 36), so it appears in scan("sess:", 35) and expires by t = 36.

Constraints

  • 0 <= len(operations) == len(arguments) <= 100,000
  • Timestamps t >= 0 are non-decreasing across the sequence of operations
  • ttl >= 0 whenever supplied; every "restore" references an existing backup_id
  • key, value, and prefix are short ASCII strings (0 <= len <= 64)
  • Narrow prefix scans can appear frequently on large key sets, so avoid scanning all stored keys on every "scan"

Step-by-step walkthrough

  1. Understand all four parts and the timing rules

    The judge calls in_memory_database(operations, arguments) and replays a list of commands against one database instance, collecting one return value per command:

    Command Arguments Return value
    put [key, value, t] or [key, value, t, ttl] None
    get [key, t] value, or None if missing/expired
    scan [prefix, t] [[key, value], ...] sorted alphabetically by key
    backup [t] integer backup_id (0, 1, 2, ...)
    restore [backup_id, t] None

    Pay close attention to the two timestamp rules:

    • Half-open TTL interval [t, t + ttl): Writing at t = 10 with ttl = 5 makes the key valid at 10, 11, 12, 13, 14, and already expired at 15 (t < expire_at, never <=). Keys written without a TTL never expire. Overwriting a key replaces both its value and its TTL.
    • Backup pauses remaining lifetime: backup(b) saves only keys still alive at time b, recording each key's remaining lifetime expire_at - b. When restore(id, r) runs at a later time r, the database resets to that snapshot and each saved key expires at r + remaining_ttl.
    put("sess:9", "ok", t=4, ttl=10)      valid on [4, 14)
    backup(t=8)                           alive! remaining_ttl = 14 - 8 = 6  -> backup 0
    put("sess:9", "tampered", t=9)        overwrites live db
    restore(id=0, t=30)                   restores "ok", valid on [30, 30 + 6) = [30, 36)
    scan("sess:", t=35) -> includes "ok"  (35 < 36)
    get("sess:9", t=36) -> None           (36 >= 36, expired)
    
  2. Why a plain dictionary is too slow for repeated scans

    A single Python dictionary data[key] = [value, expire_at] makes put and get O(1) on average, which is ideal for Parts 1 and 3.

    However, dictionaries store keys by hash rather than alphabetical order. Answering scan(prefix, t) from a plain dictionary forces us to inspect every key in the database and sort the matches, costing O(n log n) per scan when n keys are stored. With 50,000 keys and 50,000 narrow scans (such as scan("user:0042", t) returning just 9 keys), scanning the whole dictionary every time performs billions of wasted checks.

    Keeping a sorted Python list of keys alongside bisect makes scan fast, because we can binary-search for prefix, but inserting a brand-new key into the middle of a Python list shifts up to n elements (O(n) per put). We want both fast updates and fast prefix scans.

  3. Key idea: pair a hash map with a trie and lazy expiration

    We split the work between two structures that stay in sync:

    • A dictionary self.data maps key -> [value, expire_at] for instant O(1) point lookups and value updates.
    • A trie (prefix tree) self.root stores the characters of every key in self.data, one character per edge, marking node.is_key = True where a stored key ends.
    Keys stored: "a", "ab", "ac", "b"
    
              (root)
              /    \
            'a'*   'b'*        * means is_key == True
            /  \
          'b'* 'c'*
    
    Preorder walk (parent first, then children in 'a'..'z' order):
      "a" -> "ab" -> "ac" -> "b"   (exact lexicographic order!)
    

    Why does a trie make scan(prefix, t) fast? Walking the characters of prefix from the root lands directly on the subtree containing only keys that start with prefix — keys under other prefixes are never touched! Visiting each node before its children (preorder) naturally lists "a" before "ab", and visiting child edges in sorted character order lists "ab" before "ac".

    For TTLs, we use lazy expiration: instead of running background timers, we check t < expire_at whenever get or scan touches a key. Since timestamps never decrease, once a key is found expired we can permanently delete it from both self.data and the trie so future scans do not trip over dead branches.

  4. Implement storage, lazy deletion, put, and get

    When _delete(key) removes an expired key from the trie, it first unmarks node.is_key = False and then walks backward up the character path, deleting any node that neither marks another key (child.is_key) nor leads to longer keys (child.children). That keeps the trie completely free of empty dead-end chains.

    In put, be careful with ttl = 0: in Python bool(0) is False, so always test if ttl is not None: rather than if ttl:.

    from typing import Any, Dict, List, Optional, Tuple
    
    
    class TrieNode:
        def __init__(self):
            # children: {single_char: child_TrieNode}
            self.children: Dict[str, "TrieNode"] = {}
            # True when the path from the root to this node spells an active key in `data`.
            self.is_key: bool = False
    
    
    class InMemoryDB:
        def __init__(self):
            # data: {key: [value, expire_at]} where expire_at is an int timestamp, or None if permanent.
            self.data: Dict[str, List[Any]] = {}
            # Trie mirroring the exact key set of `data` so prefix scans run in sorted order.
            self.root = TrieNode()
            # backups[backup_id]: {key: (value, remaining_ttl)} where remaining_ttl is int or None.
            self.backups: List[Dict[str, Tuple[str, Optional[int]]]] = []
    
        def _is_live(self, key: str, t: int) -> bool:
            entry = self.data.get(key)
            if entry is None:
                return False
            expire_at = entry[1]
            # Half-open lifetime [write_t, expire_at): at t == expire_at the key is already expired.
            return expire_at is None or t < expire_at
    
        def _trie_add(self, key: str) -> None:
            node = self.root
            for ch in key:
                if ch not in node.children:
                    node.children[ch] = TrieNode()
                node = node.children[ch]
            node.is_key = True
    
        def _delete(self, key: str) -> None:
            """Delete an expired key from `data` and prune any now-empty branch in the trie."""
            del self.data[key]
            path: List[Tuple[TrieNode, str]] = []
            node = self.root
            for ch in key:
                path.append((node, ch))
                node = node.children[ch]
            node.is_key = False
    
            # Walk back toward the root, removing nodes that neither end a key nor have children.
            for parent, ch in reversed(path):
                child = parent.children[ch]
                if child.is_key or child.children:
                    break
                del parent.children[ch]
    
        def put(self, key: str, value: str, t: int, ttl: Optional[int] = None) -> None:
            # Only insert into the trie if `key` is not already tracked in `data`.
            if key not in self.data:
                self._trie_add(key)
    
            # Check `is not None` rather than truthiness so ttl == 0 expires immediately at `t`.
            expire_at = None
            if ttl is not None:
                expire_at = t + ttl
            self.data[key] = [value, expire_at]
    
        def get(self, key: str, t: int) -> Optional[str]:
            if key not in self.data:
                return None
            # Lazy expiration: clean up expired entries when a read encounters them.
            if not self._is_live(key, t):
                self._delete(key)
                return None
            return self.data[key][0]
    
  5. Implement sorted prefix scans on the trie

    scan(prefix, t) runs in three clean phases:

    1. Follow prefix character by character from self.root. If any character edge is missing, no stored key starts with prefix, so return [].
    2. Perform an iterative depth-first traversal using an explicit stack (avoiding Python recursion limits on long keys). Because a stack is last-in, first-out, push child characters in reverse sorted order (sorted(..., reverse=True)) so the smallest character is popped first!
    3. Record any expired keys encountered into expired_keys and delete them after the loop finishes, so we never mutate children dictionaries while iterating over them.
        def scan(self, prefix: str, t: int) -> List[List[str]]:
            # Phase 1: walk down the trie to the subtree holding all keys starting with `prefix`.
            node = self.root
            for ch in prefix:
                if ch not in node.children:
                    return []
                node = node.children[ch]
    
            # Phase 2: iterative preorder DFS yields shorter keys first ("ab" before "abc")
            # and visits sibling characters in ascending alphabetical order.
            result: List[List[str]] = []
            expired_keys: List[str] = []
            stack: List[Tuple[str, TrieNode]] = [(prefix, node)]
    
            while stack:
                key, cur = stack.pop()
                if cur.is_key:
                    if self._is_live(key, t):
                        result.append([key, self.data[key][0]])
                    else:
                        expired_keys.append(key)
                # Push children in reverse order so the stack pops the smallest character first.
                for ch in sorted(cur.children, reverse=True):
                    stack.append((key + ch, cur.children[ch]))
    
            # Phase 3: prune expired keys after finishing the traversal so we do not mutate `children` mid-walk.
            for key in expired_keys:
                self._delete(key)
            return result
    
  6. Implement backup and restore with remaining TTL

    A backup snapshot must be completely insulated from future put or _delete calls on the live database. In backup(t), we iterate through self.data:

    • Permanent keys (expire_at is None) are stored as (value, None).
    • Live TTL keys (t < expire_at) are stored with their remaining lifetime (value, expire_at - t).
    • Already-expired keys (t >= expire_at) are skipped completely.

    In restore(backup_id, t), we reset self.data and self.root (leaving self.backups intact so any backup can be restored multiple times!) and replay each saved (value, remaining_ttl) through self.put(key, value, t, remaining_ttl), which automatically computes the new expiration timestamp t + remaining_ttl and rebuilds the trie.

        def backup(self, t: int) -> int:
            # Capture immutable (value, remaining_ttl) tuples for keys still alive at time `t`.
            snapshot: Dict[str, Tuple[str, Optional[int]]] = {}
            for key, entry in self.data.items():
                value, expire_at = entry
                if expire_at is None:
                    snapshot[key] = (value, None)
                elif t < expire_at:
                    remaining_ttl = expire_at - t
                    snapshot[key] = (value, remaining_ttl)
            self.backups.append(snapshot)
            return len(self.backups) - 1
    
        def restore(self, backup_id: int, t: int) -> None:
            # Wipe live state (keeping `self.backups`) and restart each saved key's remaining TTL from `t`.
            self.data = {}
            self.root = TrieNode()
            for key, (value, remaining_ttl) in self.backups[backup_id].items():
                self.put(key, value, t, remaining_ttl)
    
  7. Wire up the operation dispatcher and trace Examples 2 and 3

    in_memory_database(operations, arguments) creates a fresh InMemoryDB, loops through zip(operations, arguments), and appends each command's output (None for put and restore).

    Let's trace Example 2 and Example 3 to confirm every detail:

    Example 2 (sorted prefix scan + expiration):
      put("item:20", "pen", 1)        trie adds path i->t->e->m->:->2->0*
      put("item:05", "notebook", 2,6) shares i->t->e->m->: then branches to 0->5* (valid [2, 8))
      put("item:1", "clip", 3)        shares i->t->e->m->: then branches to 1*
      put("other:1", "mug", 4)        under 'o', untouched by scan("item:", ...)
      scan("item:", 7)                at ':', pops '0'->'5', then '1', then '2'->'0'
                                      -> [["item:05","notebook"], ["item:1","clip"], ["item:20","pen"]]
      scan("item:", 8)                8 >= 8 so "item:05" is expired & pruned
                                      -> [["item:1","clip"], ["item:20","pen"]]
    
    Example 3 (backup + restore remaining TTL):
      put("sess:9", "ok", 4, 10)      data["sess:9"] = ["ok", 14]                      -> None
      put("sess:1", "perm", 5)        data["sess:1"] = ["perm", None]                  -> None
      backup(8)                       14 - 8 = 6 -> backups[0]={"sess:9": ("ok", 6),
                                                                "sess:1": ("perm", None)} -> 0
      put("sess:9", "tampered", 9)    data["sess:9"] = ["tampered", None]              -> None
      restore(0, 30)                  rebuilds "sess:9"->["ok", 36], "sess:1"->perm    -> None
      scan("sess:", 35)               35 < 36 -> [["sess:1","perm"], ["sess:9","ok"]]
      get("sess:9", 36)               36 >= 36 -> expired, pruned from data & trie     -> None
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class TrieNode:
        def __init__(self):
            # children: {single_char: child_TrieNode}
            self.children: Dict[str, "TrieNode"] = {}
            # True when the path from the root to this node spells an active key in `data`.
            self.is_key: bool = False
    
    
    class InMemoryDB:
        def __init__(self):
            # data: {key: [value, expire_at]} where expire_at is an int timestamp, or None if permanent.
            self.data: Dict[str, List[Any]] = {}
            # Trie mirroring the exact key set of `data` so prefix scans run in sorted order.
            self.root = TrieNode()
            # backups[backup_id]: {key: (value, remaining_ttl)} where remaining_ttl is int or None.
            self.backups: List[Dict[str, Tuple[str, Optional[int]]]] = []
    
        def _is_live(self, key: str, t: int) -> bool:
            entry = self.data.get(key)
            if entry is None:
                return False
            expire_at = entry[1]
            # Half-open lifetime [write_t, expire_at): at t == expire_at the key is already expired.
            return expire_at is None or t < expire_at
    
        def _trie_add(self, key: str) -> None:
            node = self.root
            for ch in key:
                if ch not in node.children:
                    node.children[ch] = TrieNode()
                node = node.children[ch]
            node.is_key = True
    
        def _delete(self, key: str) -> None:
            """Delete an expired key from `data` and prune any now-empty branch in the trie."""
            del self.data[key]
            path: List[Tuple[TrieNode, str]] = []
            node = self.root
            for ch in key:
                path.append((node, ch))
                node = node.children[ch]
            node.is_key = False
    
            # Walk back toward the root, removing nodes that neither end a key nor have children.
            for parent, ch in reversed(path):
                child = parent.children[ch]
                if child.is_key or child.children:
                    break
                del parent.children[ch]
    
        def put(self, key: str, value: str, t: int, ttl: Optional[int] = None) -> None:
            # Only insert into the trie if `key` is not already tracked in `data`.
            if key not in self.data:
                self._trie_add(key)
    
            # Check `is not None` rather than truthiness so ttl == 0 expires immediately at `t`.
            expire_at = None
            if ttl is not None:
                expire_at = t + ttl
            self.data[key] = [value, expire_at]
    
        def get(self, key: str, t: int) -> Optional[str]:
            if key not in self.data:
                return None
            # Lazy expiration: clean up expired entries when a read encounters them.
            if not self._is_live(key, t):
                self._delete(key)
                return None
            return self.data[key][0]
    
        def scan(self, prefix: str, t: int) -> List[List[str]]:
            # Phase 1: walk down the trie to the subtree holding all keys starting with `prefix`.
            node = self.root
            for ch in prefix:
                if ch not in node.children:
                    return []
                node = node.children[ch]
    
            # Phase 2: iterative preorder DFS yields shorter keys first ("ab" before "abc")
            # and visits sibling characters in ascending alphabetical order.
            result: List[List[str]] = []
            expired_keys: List[str] = []
            stack: List[Tuple[str, TrieNode]] = [(prefix, node)]
    
            while stack:
                key, cur = stack.pop()
                if cur.is_key:
                    if self._is_live(key, t):
                        result.append([key, self.data[key][0]])
                    else:
                        expired_keys.append(key)
                # Push children in reverse order so the stack pops the smallest character first.
                for ch in sorted(cur.children, reverse=True):
                    stack.append((key + ch, cur.children[ch]))
    
            # Phase 3: prune expired keys after finishing the traversal so we do not mutate `children` mid-walk.
            for key in expired_keys:
                self._delete(key)
            return result
    
        def backup(self, t: int) -> int:
            # Capture immutable (value, remaining_ttl) tuples for keys still alive at time `t`.
            snapshot: Dict[str, Tuple[str, Optional[int]]] = {}
            for key, entry in self.data.items():
                value, expire_at = entry
                if expire_at is None:
                    snapshot[key] = (value, None)
                elif t < expire_at:
                    remaining_ttl = expire_at - t
                    snapshot[key] = (value, remaining_ttl)
            self.backups.append(snapshot)
            return len(self.backups) - 1
    
        def restore(self, backup_id: int, t: int) -> None:
            # Wipe live state (keeping `self.backups`) and restart each saved key's remaining TTL from `t`.
            self.data = {}
            self.root = TrieNode()
            for key, (value, remaining_ttl) in self.backups[backup_id].items():
                self.put(key, value, t, remaining_ttl)
    
    
    def in_memory_database(operations: List[str], arguments: List[List]) -> List:
        db = InMemoryDB()
        results = []
        for op, args in zip(operations, arguments):
            if op == "put":
                ttl = args[3] if len(args) > 3 else None
                db.put(args[0], args[1], args[2], ttl)
                results.append(None)
            elif op == "get":
                results.append(db.get(args[0], args[1]))
            elif op == "scan":
                results.append(db.scan(args[0], args[1]))
            elif op == "backup":
                results.append(db.backup(args[0]))
            elif op == "restore":
                db.restore(args[0], args[1])
                results.append(None)
            else:
                raise ValueError(f"unknown operation: {op}")
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of the database as two tools working side by side: a hash map (dictionary) acting like a locker room where you jump straight to locker "sess:1" for its current value and expiration time, and a trie (also called a prefix tree — a tree where each edge is one character so strings sharing a prefix share the same starting path from the root) acting like alphabetical thumb-tabs in a physical dictionary. Every entry's TTL (time-to-live, the number of time units a record stays valid before automatically expiring) works like a countdown timer on a half-open interval [t, t + ttl) (meaning start time t is included, while end time t + ttl is already expired), and taking a backup is like photographing only the still-ticking timers along with how many seconds each one has left, then unpausing those countdowns when restore runs.

A naive implementation stores only the dictionary and implements scan(prefix, t) by checking key.startswith(prefix) across every key in the database and sorting the matches. When 40,000 keys sit in memory and thousands of narrow scans ask for a tiny prefix like "user:0042", scanning and sorting all 40,000 keys every single time wastes hundreds of millions of string comparisons. Keeping a sorted array fixes scans via binary search, but inserting new keys shifts the array in O(n) time per put.

Pairing the dictionary with the trie gives fast writes and fast lexicographic order (standard alphabetical/dictionary order, where "a" < "ab" < "ac" < "b"), while lazy expiration (checking whether a key has expired only when a read touches it, then deleting and pruning its empty trie branch) avoids running background timers:

  • put("ab", "1", t=10, ttl=5) stores data["ab"] = ["1", 15] and creates the path root -> 'a' -> 'b' (is_key = True).
  • put("a", "2", t=11) stores data["a"] = ["2", None] and marks the existing 'a' node is_key = True.
  • scan("a", t=12) walks to 'a' and runs a preorder traversal (visiting a node itself before its children, with child characters visited from smallest to largest), returning [["a", "2"], ["ab", "1"]] without touching keys under 'b'..'z'.
  • backup(t=13) sees "ab" has 15 - 13 = 2 units left and "a" has None, saving {"ab": ("1", 2), "a": ("2", None)} as backup 0.
  • restore(0, t=20) rebuilds both structures so "ab" now expires at 20 + 2 = 22 and "a" remains permanent.

Complexity

Let L be the length of a key, n be the number of keys currently stored, and k be the number of stored keys in self.data that start with a scan's prefix.

  • put: O(L) average time. Hashing key into self.data takes O(L), and inserting a new key into the trie walks or creates at most L character nodes.
  • get: O(L) average time. Looking up key in self.data takes O(L) to hash the string, plus at most O(L) steps up the trie to prune dead nodes when an expired key is lazily deleted.
  • scan: O(|prefix| + k * L^2) worst-case time (O(|prefix| + k * L) node visits). Walking to the prefix node takes O(|prefix|) steps. Because _delete prunes empty branches, every node inside that subtree belongs to at least one of the k matching stored keys, visiting at most k * L nodes (sorting each node's children over the bounded character alphabet and building key + ch strings of length up to L). Any expired keys among those k are deleted at the end of the scan, so each expired key is visited by at most one read across its lifetime.
  • backup: O(n) time and O(live_keys) space. We scan the n entries in self.data once and copy only the still-live (value, remaining_ttl) pairs into the snapshot dictionary.
  • restore: O(S) time, where S is the total character length of all keys in the chosen snapshot, because replaying put inserts every saved key back into self.data and the fresh trie.
  • Space: O(total live key/value characters + sum of snapshot sizes) across self.data, the trie nodes, and self.backups.

Edge cases

  • Exact expiration boundary (t == write_t + ttl): Because [t, t + ttl) is half-open, put("a", "x", 5, 3) is live at t = 7 and already expired at t = 8.
  • Zero TTL (ttl == 0): The interval [t, t) is empty, so put("z", "w", 8, 0) is invisible even at t = 8. Testing if ttl is not None: avoids treating 0 as "no TTL".
  • Overwriting a TTL key without a TTL (or vice versa): A new put completely replaces [value, expire_at], so overwriting a temporary key without ttl makes it permanent, and overwriting an uncleaned expired key revives it cleanly.
  • Prefix equals a stored key ("a" alongside "ab" and "abc"): Preorder traversal checks cur.is_key before pushing cur's children, placing "a" before "ab" and "abc".
  • Empty prefix "": Stays at self.root and returns every live key in the database in sorted order.
  • Restoring the same backup multiple times: Because self.backups[id] stores immutable (value, remaining_ttl) tuples rather than mutating in place, restoring backup 0 at t = 20 and again at t = 30 gives the entry remaining_ttl fresh units from 20 the first time and from 30 the second time.

Common mistakes

  • Using t <= expire_at instead of t < expire_at: Off-by-one check that keeps keys alive at t + ttl when the half-open interval [t, t + ttl) has already ended.
  • Testing if ttl: instead of if ttl is not None:: In Python 0 is falsy, so ttl = 0 would mistakenly set expire_at = None (never expires!) instead of expiring immediately.
  • Saving absolute expire_at or original ttl in backup: Saving expire_at = 14 makes a key restored at t = 30 immediately dead (failing Example 3), while saving the original ttl = 10 resets the countdown instead of preserving the remaining 6 units.
  • Aliasing mutable [value, expire_at] lists inside backup: Doing snapshot = self.data.copy() shares the inner lists, allowing later put calls to corrupt historical backups.
  • Pushing trie children in ascending order onto a LIFO stack: Pushing '1' then '2' pops '2' first and outputs keys in reverse alphabetical order; push sorted(..., reverse=True) so the smallest character pops first.
  • Deleting from the trie while iterating over it in scan: Collect expired_keys during the stack walk and call _delete afterward so child dictionaries never shrink mid-iteration.

Alternative approaches

  • Dictionary + sort on every scan: Very short to write (O(1) put/get, O(n log n) scan), great as a brute-force reference in tests, but too slow when many scans run over a large key set.
  • Balanced binary search tree / sorted container (such as Java TreeMap or C++ std::map): Stores keys directly in sorted order with O(log n) string comparisons per put/get and O(log n + k) per scan, without building per-character trie nodes. Python's standard library has no built-in balanced search tree, making a hash map + trie the cleanest pure-stdlib choice.

Follow-up questions

  • How could you achieve O(1) time for both backup and restore instead of copying every active record? Use a persistent data structure (an immutable tree or trie where every put copies only the O(L) nodes along the modified root-to-leaf path and shares all unchanged subtrees with older versions). To handle shifting TTLs without touching every saved key on restore, store timestamps on a virtual clock virtual_t = real_t - clock_offset: a backup at b saves (root_pointer, virtual_b) in O(1), and restoring it at r simply restores root_pointer and updates clock_offset = r - virtual_b so every surviving key's remaining lifetime is preserved automatically!
  • How would you add cursor-based pagination to scan when millions of keys share the target prefix? Accept an optional cursor string holding the last key returned on the previous page, and resume the trie walk strictly after cursor (at each depth along cursor, only push sibling characters greater than cursor[depth], then stop as soon as limit live keys are collected). Clarify with the interviewer whether pagination should see live writes between pages (stateless cursor) or a consistent point-in-time view (run against a lightweight persistent snapshot).
  • How would your design change if read and write operations could arrive with out-of-order timestamps? Lazy deletion is no longer safe because a key expired at t = 20 might still be queried by a late-arriving get(key, t=15). Instead, store a per-key list of version tuples (write_t, expire_at, value) sorted by write_t, use binary search on get(key, t) to find the latest write with write_t <= t, and check t < expire_at on that version; old versions can only be garbage-collected once a low-watermark timestamp guarantees no older queries will arrive.

Follow-up questions

Similar questions

More Coinbase interview questions

All 99 Coinbase questions →