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
valueunder stringkeyat integer timestampt, and appendsNoneto the output list. - If
ttlis omitted, the record never expires. - If integer
ttlis supplied, the record stays live strictly over the half-open time window[t, t + ttl): reads at timestampqsee it whileq < t + ttl, and it is expired as soon asq >= t + ttl(sottl == 0expires immediately att). - Calling
"put"on an existing key replaces both its value and its expiration rule (for example, overwriting a expiring key withoutttlmakes it permanent).
- Stores string
"get"with[key, t]:- Appends the current string
valuestored atkeyifkeyexists and is still live at timestampt, orNoneif missing or expired.
- Appends the current string
"scan"with[prefix, t]:- Appends a list of
[key, value]pairs for every live record at timestamptwhosekeybegins withprefix(including exact matcheskey == prefixand emptyprefix == ""), sorted in ascending lexicographical order bykey.
- Appends a list of
"backup"with[t]:- Saves a snapshot of every record that is still live at timestamp
t(excluding records already expired byt). - Assigns sequential
0-based integer IDs (0,1,2, ...) to backups in creation order and appends the newly createdbackup_id. - For each live expiring record, the snapshot records its remaining lifetime (
expire_at - t) rather than resetting to its full initialttl.
- Saves a snapshot of every record that is still live at timestamp
"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 appendsNone. - Permanent records in that snapshot stay permanent; records saved with
remaining_ttlunits left resume counting down fromtand stay live on[t, t + remaining_ttl).
- Replaces the entire live database state with the snapshot identified by
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 att = 3. Att = 5, it is overwritten with"prod"andttl = 4, making it valid on[5, 9):getreturns"prod"att = 8andNoneoncet = 9reaches 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". Byt = 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). Whenbackup(8)creates snapshot0,"sess:9"has14 - 8 = 6time units remaining and"sess:1"is permanent. Restoring snapshot0att = 30discards"tampered"and makes"sess:9"valid on[30, 36), so it appears inscan("sess:", 35)and expires byt = 36.
Constraints
0 <= len(operations) == len(arguments) <= 100,000- Timestamps
t >= 0are non-decreasing across the sequence of operations ttl >= 0whenever supplied; every"restore"references an existingbackup_idkey,value, andprefixare 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
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]Noneget[key, t]value, orNoneif missing/expiredscan[prefix, t][[key, value], ...]sorted alphabetically bykeybackup[t]integer backup_id(0,1,2, ...)restore[backup_id, t]NonePay close attention to the two timestamp rules:
- Half-open TTL interval
[t, t + ttl): Writing att = 10withttl = 5makes the key valid at10, 11, 12, 13, 14, and already expired at15(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 timeb, recording each key's remaining lifetimeexpire_at - b. Whenrestore(id, r)runs at a later timer, the database resets to that snapshot and each saved key expires atr + 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)- Half-open TTL interval
Why a plain dictionary is too slow for repeated scans
A single Python dictionary
data[key] = [value, expire_at]makesputandgetO(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, costingO(n log n)per scan whennkeys are stored. With50,000keys and50,000narrow scans (such asscan("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
bisectmakesscanfast, because we can binary-search forprefix, but inserting a brand-new key into the middle of a Python list shifts up tonelements (O(n)perput). We want both fast updates and fast prefix scans.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.datamapskey -> [value, expire_at]for instantO(1)point lookups and value updates. - A trie (prefix tree)
self.rootstores the characters of every key inself.data, one character per edge, markingnode.is_key = Truewhere 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 ofprefixfrom the root lands directly on the subtree containing only keys that start withprefix— 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_atwhenevergetorscantouches a key. Since timestamps never decrease, once a key is found expired we can permanently delete it from bothself.dataand the trie so future scans do not trip over dead branches.- A dictionary
Implement storage, lazy deletion, put, and get
When
_delete(key)removes an expired key from the trie, it first unmarksnode.is_key = Falseand 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 withttl = 0: in Pythonbool(0)isFalse, so always testif ttl is not None:rather thanif 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]Implement sorted prefix scans on the trie
scan(prefix, t)runs in three clean phases:- Follow
prefixcharacter by character fromself.root. If any character edge is missing, no stored key starts withprefix, so return[]. - 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! - Record any expired keys encountered into
expired_keysand delete them after the loop finishes, so we never mutatechildrendictionaries 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- Follow
Implement backup and restore with remaining TTL
A backup snapshot must be completely insulated from future
putor_deletecalls on the live database. Inbackup(t), we iterate throughself.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 resetself.dataandself.root(leavingself.backupsintact so any backup can be restored multiple times!) and replay each saved(value, remaining_ttl)throughself.put(key, value, t, remaining_ttl), which automatically computes the new expiration timestampt + remaining_ttland 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)- Permanent keys (
Wire up the operation dispatcher and trace Examples 2 and 3
in_memory_database(operations, arguments)creates a freshInMemoryDB, loops throughzip(operations, arguments), and appends each command's output (Noneforputandrestore).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 -> NoneComplete 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)storesdata["ab"] = ["1", 15]and creates the pathroot -> 'a' -> 'b'(is_key = True).put("a", "2", t=11)storesdata["a"] = ["2", None]and marks the existing'a'nodeis_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"has15 - 13 = 2units left and"a"hasNone, saving{"ab": ("1", 2), "a": ("2", None)}as backup0.restore(0, t=20)rebuilds both structures so"ab"now expires at20 + 2 = 22and"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. Hashingkeyintoself.datatakesO(L), and inserting a new key into the trie walks or creates at mostLcharacter nodes.get:O(L)average time. Looking upkeyinself.datatakesO(L)to hash the string, plus at mostO(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 takesO(|prefix|)steps. Because_deleteprunes empty branches, every node inside that subtree belongs to at least one of thekmatching stored keys, visiting at mostk * Lnodes (sorting each node's children over the bounded character alphabet and buildingkey + chstrings of length up toL). Any expired keys among thosekare 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 andO(live_keys)space. We scan thenentries inself.dataonce and copy only the still-live(value, remaining_ttl)pairs into the snapshot dictionary.restore:O(S)time, whereSis the total character length of all keys in the chosen snapshot, because replayingputinserts every saved key back intoself.dataand the fresh trie.- Space:
O(total live key/value characters + sum of snapshot sizes)acrossself.data, the trie nodes, andself.backups.
Edge cases
- Exact expiration boundary (
t == write_t + ttl): Because[t, t + ttl)is half-open,put("a", "x", 5, 3)is live att = 7and already expired att = 8. - Zero TTL (
ttl == 0): The interval[t, t)is empty, soput("z", "w", 8, 0)is invisible even att = 8. Testingif ttl is not None:avoids treating0as "no TTL". - Overwriting a TTL key without a TTL (or vice versa): A new
putcompletely replaces[value, expire_at], so overwriting a temporary key withoutttlmakes it permanent, and overwriting an uncleaned expired key revives it cleanly. - Prefix equals a stored key (
"a"alongside"ab"and"abc"): Preorder traversal checkscur.is_keybefore pushingcur's children, placing"a"before"ab"and"abc". - Empty prefix
"": Stays atself.rootand 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 backup0att = 20and again att = 30gives the entryremaining_ttlfresh units from20the first time and from30the second time.
Common mistakes
- Using
t <= expire_atinstead oft < expire_at: Off-by-one check that keeps keys alive att + ttlwhen the half-open interval[t, t + ttl)has already ended. - Testing
if ttl:instead ofif ttl is not None:: In Python0is falsy, sottl = 0would mistakenly setexpire_at = None(never expires!) instead of expiring immediately. - Saving absolute
expire_ator originalttlinbackup: Savingexpire_at = 14makes a key restored att = 30immediately dead (failing Example 3), while saving the originalttl = 10resets the countdown instead of preserving the remaining6units. - Aliasing mutable
[value, expire_at]lists insidebackup: Doingsnapshot = self.data.copy()shares the inner lists, allowing laterputcalls 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; pushsorted(..., reverse=True)so the smallest character pops first. - Deleting from the trie while iterating over it in
scan: Collectexpired_keysduring the stack walk and call_deleteafterward 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
TreeMapor C++std::map): Stores keys directly in sorted order withO(log n)string comparisons perput/getandO(log n + k)perscan, 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
putcopies only theO(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 onrestore, store timestamps on a virtual clockvirtual_t = real_t - clock_offset: a backup atbsaves(root_pointer, virtual_b)inO(1), and restoring it atrsimply restoresroot_pointerand updatesclock_offset = r - virtual_bso 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
cursorstring holding the last key returned on the previous page, and resume the trie walk strictly aftercursor(at each depth alongcursor, only push sibling characters greater thancursor[depth], then stop as soon aslimitlive 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 = 20might still be queried by a late-arrivingget(key, t=15). Instead, store a per-key list of version tuples(write_t, expire_at, value)sorted bywrite_t, use binary search onget(key, t)to find the latest write withwrite_t <= t, and checkt < expire_aton that version; old versions can only be garbage-collected once a low-watermark timestamp guarantees no older queries will arrive.
Follow-up questions
- How could you achieve O(1) time for both backup and restore instead of copying every active record?
- How would you add cursor-based pagination to scan when millions of keys share the target prefix?
- How would your design change if read and write operations could arrive with out-of-order timestamps?
Similar questions
- Meal Dispatch and Time-Window Order Analytics
- Cumulative Distance Along a Circular Ring
- Users Exceeding a Connection Threshold
- Trading Order State Transition Controller
- Order Lifecycle Store with Idempotent State Transitions
- Sequence Pattern Inference with Single-Element Repair
More Coinbase interview questions
- Greedy Block Packing with Ancestor Fee Packages Medium
- Greedy Block Assembly with Ancestor Fee Packages Hard
- Staff-Level Frontend Architecture Deep Dive Hard Pro
- Regional Adoption Rates and Cross-Region Activity Medium Pro
- Marketplace Basket Routing and Windowed Analytics Medium Pro
- Fixing and Extending an In-Memory Query Cursor Hard Pro
- Balancing Delivery Speed Against Automated Test Rigor Medium Pro
- Presenting a Well-Crafted Software Component Medium Pro
- Cryptocurrency Order Placement and Routing Hard Pro
- Web Trading Terminal Frontend Architecture Hard Pro