In-Memory Key-Field Store with Expiring Entries and Snapshots

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

Build an in-memory two-level dictionary store where each top-level key maps to named field entries holding string values, with per-field expiration deadlines and point-in-time snapshots. Every call supplies the current clock value timestamp as an integer that never decreases from one call to the next.

Implement a class InMemoryDB supporting five operations, together with the replay function run_in_memory_db(operations: List[str], arguments: List[List]) -> List:

  • set(timestamp: int, key: str, field: str, value: str, ttl: int = 0) -> None — Stores value at (key, field). When ttl > 0, the entry stays readable during [timestamp, timestamp + ttl) and becomes expired once the clock reaches timestamp + ttl. When ttl == 0 (the default if omitted), the entry has no expiration deadline. Writing to an already-present (key, field) replaces its string and resets or removes its deadline.
  • get(timestamp: int, key: str, field: str) -> Optional[str] — Looks up (key, field) at timestamp, returning its string if present and still unexpired (timestamp < deadline), or None if absent or expired (timestamp >= deadline).
  • delete(timestamp: int, key: str, field: str) -> bool — Erases field from key, returning True only when that field was present and unexpired at timestamp (False otherwise).
  • backup(timestamp: int) -> int — Captures an independent checkpoint containing all entries that are unexpired at timestamp, assigns it the next integer ID in 1, 2, 3, ..., and returns that ID.
  • restore(timestamp: int, backup_id: int) -> bool — Replaces the live store with checkpoint backup_id and returns True, or leaves live data untouched and returns False when backup_id does not match an existing checkpoint. Restored entries keep the exact wall-clock expiration deadlines computed when they were originally written: any entry whose deadline is <= timestamp is already expired upon restoration, and later writes must not alter saved checkpoints.

run_in_memory_db(operations, arguments) starts with an empty InMemoryDB, dispatches each operations[i] with argument list arguments[i] (for "set", arguments[i] has length 4 when ttl defaults to 0, or length 5 when ttl is supplied), and returns the list of outputs (None for every "set").

Examples

Example 1

Input:
  operations = [
    "set", "set", "get", "backup",
    "set", "delete", "get",
    "restore", "get", "get", "get"
  ]
  arguments = [
    [2, "acct:9", "token", "tk_alpha", 8],
    [2, "acct:9", "tier", "pro", 0],
    [5, "acct:9", "token"],
    [6],
    [7, "acct:9", "token", "tk_beta", 0],
    [8, "acct:9", "tier"],
    [8, "acct:9", "token"],
    [9, 1],
    [9, "acct:9", "token"],
    [10, "acct:9", "token"],
    [10, "acct:9", "tier"]
  ]
Output:
  [None, None, "tk_alpha", 1, None, True, "tk_beta", True, "tk_alpha", None, "pro"]

Explanation: At t = 2, "token" gets deadline 2 + 8 = 10 while "tier" is permanent (ttl = 0). Checkpoint 1 is saved at t = 6. Later writes overwrite "token" with "tk_beta" and delete "tier". Restoring checkpoint 1 at t = 9 brings back "token" ("tk_alpha", still readable at t = 9 since 9 < 10, then None at t = 10) alongside permanent "tier" ("pro").

Example 2

Input:
  operations = ["set", "delete", "backup", "restore", "get"]
  arguments = [
    [3, "cfg:1", "host", "db01", 4],
    [7, "cfg:1", "host"],
    [8],
    [9, 2],
    [9, "cfg:1", "host"]
  ]
Output:
  [None, False, 1, False, None]

Explanation: "host" is written at t = 3 with ttl = 4, so its deadline is 7. By t = 7 it has already expired, making delete return False. Checkpoint 1 is taken at t = 8; asking to restore nonexistent backup_id = 2 at t = 9 returns False.

Constraints

  • 1 <= timestamp <= 10^9, and timestamps across arguments are non-decreasing.
  • key, field, and value are strings of 1 to 64 ASCII letters, digits, and colons (:).
  • 0 <= ttl <= 10^6.
  • 1 <= len(operations) == len(arguments) <= 20,000.
  • Combined "backup" and "restore" invocations do not exceed 100.

Step-by-step walkthrough

  1. Understand the two-level database and rules

    Our database stores strings inside a two-level hierarchy: an outer key (such as "acct:9") maps to a group of named fields (such as "token" or "tier"), and each field holds a string value. Every method call receives the current timestamp, and timestamps are guaranteed to be non-decreasing across calls.

    key ("acct:9")
      ├── field "token" -> value "tk_alpha" (expires at timestamp 10)
      └── field "tier"  -> value "pro"      (never expires)
    

    Let us pin down the exact rules for all five methods:

    • set(timestamp, key, field, value, ttl=0): stores value at (key, field). When ttl > 0, the field expires at timestamp + ttl; when ttl == 0, it never expires. Writing to an existing field overwrites both its value and its expiration.
    • get(timestamp, key, field): returns value if the field exists and is still alive, or None if it is missing or expired (timestamp >= expire_at).
    • delete(timestamp, key, field): removes the field and returns True only if it existed and was still alive at timestamp (False otherwise).
    • backup(timestamp): saves a snapshot of all currently alive fields and returns a sequential backup_id (1, 2, 3, ...).
    • restore(timestamp, backup_id): replaces the live database with snapshot backup_id (returning False if the ID is invalid). Restored fields keep their original absolute expiration timestamps.

    The judge calls run_in_memory_db(operations, arguments) and expects one output per operation (None for set, and the method's return value for everything else).

  2. Store absolute expiration times instead of remaining durations

    A beginner trap is storing the raw ttl duration (like 10). If you only store 10, then get does not know when the 10 seconds started unless you also store the write timestamp, and restore becomes confusing.

    Instead, convert ttl into an absolute deadline expire_at = timestamp + ttl the moment set is called (or None when ttl == 0):

    set(timestamp=2, ..., ttl=8)  -->  expire_at = 2 + 8 = 10
    
    timestamp:   2 .... 5 .... 9  | 10 .... 12
    status:      alive  alive  alive | expired (timestamp >= 10)
    

    Storing expire_at buys us two big wins at once: 1. Checking whether a field is alive is a single comparison: expire_at is None or timestamp < expire_at. 2. When a backup is restored later, each field keeps its original wall-clock deadline—which means expire_at needs zero adjustment on restore!

    class InMemoryDB:
        def __init__(self) -> None:
            # Outer dict maps key -> inner dict of {field: (value, expire_at)}.
            # Mini-shape: {"acct:9": {"token": ("tk_alpha", 10), "tier": ("pro", None)}}
            # expire_at is an absolute timestamp (timestamp + ttl), or None when ttl == 0.
            self.data = {}
            # self.backups[i] holds the snapshot dictionary for backup_id == i + 1 (1-indexed).
            self.backups = []
    
        def _is_alive(self, expire_at, timestamp) -> bool:
            # A field expires at timestamp >= expire_at, so it is alive strictly before expire_at.
            return expire_at is None or timestamp < expire_at
    
  3. Implement set, get, and delete

    With self.data and _is_alive in place, the three single-field operations are direct hash-map lookups:

    • set computes expire_at (timestamp + ttl if ttl > 0, else None) and assigns (value, expire_at) to self.data[key][field]. Assigning a new tuple automatically overwrites any previous value and clears or updates any old TTL.
    • get looks up (key, field) and returns None if the key is missing, the field is missing, or _is_alive is False.
    • delete removes the field if present in self.data[key]. What if the field is still sitting in self.data[key] past its expiration time? Because timestamps never move backward, an expired field can never become readable again, so popping it is completely safe—we just return self._is_alive(expire_at, timestamp) (False when expired, True when alive). If self.data[key] becomes empty, we also delete key so empty dictionaries do not accumulate.
        def set(self, timestamp: int, key: str, field: str, value: str, ttl: int = 0) -> None:
            # Convert a positive TTL into an absolute deadline; ttl == 0 means no expiration.
            expire_at = timestamp + ttl if ttl > 0 else None
            if key not in self.data:
                self.data[key] = {}
            # Overwriting replaces both the stored string and any previous expiration deadline.
            self.data[key][field] = (value, expire_at)
    
        def get(self, timestamp: int, key: str, field: str):
            fields = self.data.get(key)
            if fields is None or field not in fields:
                return None
            value, expire_at = fields[field]
            if not self._is_alive(expire_at, timestamp):
                return None
            return value
    
        def delete(self, timestamp: int, key: str, field: str) -> bool:
            fields = self.data.get(key)
            if fields is None or field not in fields:
                return False
            # Pop even if expired: timestamps never decrease, so an expired field can never come back to life.
            _value, expire_at = fields.pop(field)
            if not fields:
                del self.data[key]
            return self._is_alive(expire_at, timestamp)
    
  4. Why snapshots need two-level copies on both backup and restore

    Suppose we wrote self.backups.append(dict(self.data)) for backup. That is a shallow copy: it creates a new outer dictionary, but both outer dictionaries still point to the same inner {field: (value, expire_at)} dictionary!

    Shallow copy bug (WRONG):
      self.data["acct:9"] ──────┐
                                ├──> {"token": ("tk_beta", None)}   <-- set() overwrote snapshot 1!
      backups[0]["acct:9"] ─────┘
    
    Two-level copy (RIGHT):
      self.data["acct:9"]  ──> {"token": ("tk_beta", None)}
      backups[0]["acct:9"] ──> {"token": ("tk_alpha", 10), "tier": ("pro", None)}
    

    The exact same bug happens in reverse if restore sets self.data = self.backups[backup_id - 1] without copying: the next set would mutate self.backups[backup_id - 1], breaking any future restore to that same backup_id.

    So we write one helper _copy_alive(source, timestamp) and call it in both backup and restore: - It allocates fresh outer and inner dictionaries, keeping only fields that are alive at timestamp. - Each (value, expire_at) pair is an immutable Python tuple of a string and an int/None, so sharing the tuple itself is completely safe.

        def _copy_alive(self, source, timestamp):
            """Build a fresh two-level copy of `source` keeping only fields alive at `timestamp`."""
            snapshot = {}
            for key, fields in source.items():
                alive_fields = {}
                for field, (value, expire_at) in fields.items():
                    if self._is_alive(expire_at, timestamp):
                        # (value, expire_at) is an immutable tuple of str and int/None, so sharing it is safe.
                        alive_fields[field] = (value, expire_at)
                if alive_fields:
                    snapshot[key] = alive_fields
            return snapshot
    
  5. Implement backup and restore

    We store snapshots in the list self.backups, so backup_id 1 lives at index 0, backup_id 2 lives at index 1, and in general backup_id b lives at self.backups[b - 1].

    Watch out for Python's negative list indexing! If backup_id is 0 or -1 and you only check backup_id <= len(self.backups), then self.backups[backup_id - 1] silently reads from the back of the list instead of failing. Always check backup_id < 1 or backup_id > len(self.backups) first.

        def backup(self, timestamp: int) -> int:
            # Copy only currently active records so snapshots neither bloat nor share mutable dicts with self.data.
            self.backups.append(self._copy_alive(self.data, timestamp))
            return len(self.backups)
    
        def restore(self, timestamp: int, backup_id: int) -> bool:
            # Guard backup_id < 1 explicitly so negative IDs do not index from the end of self.backups.
            if backup_id < 1 or backup_id > len(self.backups):
                return False
            # Copy again on restore so future writes mutate self.data without corrupting the stored snapshot.
            saved_snapshot = self.backups[backup_id - 1]
            self.data = self._copy_alive(saved_snapshot, timestamp)
            return True
    

    How fast is this? There are at most 20,000 total operations (so at most 20,000 fields) and at most 100 backup/restore calls, meaning _copy_alive copies at most 100 * 20,000 = 2,000,000 field entries across the entire test run—well within a fraction of a second.

  6. Wire up the operation dispatcher

    Finally, run_in_memory_db instantiates InMemoryDB and replays each (op, args) pair. Notice that set has an optional ttl: int = 0 parameter, so args for "set" may have either 4 elements or 5 elements.

    def run_in_memory_db(operations: List[str], arguments: List[List]) -> List:
        db = InMemoryDB()
        results = []
    
        # Replay each operation in timestamp order and collect its return value (None for set).
        for op, args in zip(operations, arguments):
            if op == "set":
                timestamp, key, field, value = args[0], args[1], args[2], args[3]
                ttl = args[4] if len(args) > 4 else 0
                db.set(timestamp, key, field, value, ttl)
                results.append(None)
            elif op == "get":
                timestamp, key, field = args[0], args[1], args[2]
                results.append(db.get(timestamp, key, field))
            elif op == "delete":
                timestamp, key, field = args[0], args[1], args[2]
                results.append(db.delete(timestamp, key, field))
            elif op == "backup":
                timestamp = args[0]
                results.append(db.backup(timestamp))
            elif op == "restore":
                timestamp, backup_id = args[0], args[1]
                results.append(db.restore(timestamp, backup_id))
            else:
                raise ValueError(f"Unknown operation: {op}")
    
        return results
    
  7. Trace through Example 1 step by step

    Let us trace Example 1 to see self.data, self.backups, and absolute expiration working together:

    Call                                      Live self.data["acct:9"]                      backups[0]["acct:9"]               Out
    ----------------------------------------  --------------------------------------------  ---------------------------------  ----------
    set(2, "acct:9", "token", "tk_alpha", 8)  {"token": ("tk_alpha", 10)}                   -                                  None
    set(2, "acct:9", "tier", "pro", 0)        {"token": ("tk_alpha", 10), "tier": (..,None)} -                                 None
    get(5, "acct:9", "token")                 5 < 10 -> alive                               -                                  "tk_alpha"
    backup(6)                                 unchanged                                     {"token": (..,10), "tier": ..}     1
    set(7, "acct:9", "token", "tk_beta", 0)   {"token": ("tk_beta", None), "tier": ..}      unchanged                          None
    delete(8, "acct:9", "tier")               {"token": ("tk_beta", None)}                  unchanged                          True
    get(8, "acct:9", "token")                 expire_at is None -> alive                    unchanged                          "tk_beta"
    restore(9, 1)                             {"token": ("tk_alpha", 10), "tier": ..}       unchanged                          True
    get(9, "acct:9", "token")                 9 < 10 -> alive                               unchanged                          "tk_alpha"
    get(10, "acct:9", "token")                10 >= 10 -> expired!                          unchanged                          None
    get(10, "acct:9", "tier")                 expire_at is None -> alive                    unchanged                          "pro"
    

    Look at the final three lines: restoring snapshot 1 at t = 9 brought "tk_alpha" back with its original expire_at = 10 (plus deleted "tier"), so "token" was still readable at t = 9, expired on schedule at t = 10, and "tier" remained "pro".

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class InMemoryDB:
        def __init__(self) -> None:
            # Outer dict maps key -> inner dict of {field: (value, expire_at)}.
            # Mini-shape: {"acct:9": {"token": ("tk_alpha", 10), "tier": ("pro", None)}}
            # expire_at is an absolute timestamp (timestamp + ttl), or None when ttl == 0.
            self.data: Dict[str, Dict[str, Tuple[str, Optional[int]]]] = {}
            # self.backups[i] holds the snapshot dictionary for backup_id == i + 1 (1-indexed).
            self.backups: List[Dict[str, Dict[str, Tuple[str, Optional[int]]]]] = []
    
        def _is_alive(self, expire_at: Optional[int], timestamp: int) -> bool:
            # A field expires at timestamp >= expire_at, so it is alive strictly before expire_at.
            return expire_at is None or timestamp < expire_at
    
        def _copy_alive(
            self,
            source: Dict[str, Dict[str, Tuple[str, Optional[int]]]],
            timestamp: int,
        ) -> Dict[str, Dict[str, Tuple[str, Optional[int]]]]:
            """Build a fresh two-level copy of `source` keeping only fields alive at `timestamp`."""
            snapshot: Dict[str, Dict[str, Tuple[str, Optional[int]]]] = {}
            for key, fields in source.items():
                alive_fields: Dict[str, Tuple[str, Optional[int]]] = {}
                for field, (value, expire_at) in fields.items():
                    if self._is_alive(expire_at, timestamp):
                        # (value, expire_at) is an immutable tuple of str and int/None, so sharing it is safe.
                        alive_fields[field] = (value, expire_at)
                if alive_fields:
                    snapshot[key] = alive_fields
            return snapshot
    
        def set(self, timestamp: int, key: str, field: str, value: str, ttl: int = 0) -> None:
            # Convert a positive TTL into an absolute deadline; ttl == 0 means no expiration.
            expire_at: Optional[int] = timestamp + ttl if ttl > 0 else None
            if key not in self.data:
                self.data[key] = {}
            # Overwriting replaces both the stored string and any previous expiration deadline.
            self.data[key][field] = (value, expire_at)
    
        def get(self, timestamp: int, key: str, field: str) -> Optional[str]:
            fields = self.data.get(key)
            if fields is None or field not in fields:
                return None
            value, expire_at = fields[field]
            if not self._is_alive(expire_at, timestamp):
                return None
            return value
    
        def delete(self, timestamp: int, key: str, field: str) -> bool:
            fields = self.data.get(key)
            if fields is None or field not in fields:
                return False
            # Pop even if expired: timestamps never decrease, so an expired field can never come back to life.
            _value, expire_at = fields.pop(field)
            if not fields:
                del self.data[key]
            return self._is_alive(expire_at, timestamp)
    
        def backup(self, timestamp: int) -> int:
            # Copy only currently active records so snapshots neither bloat nor share mutable dicts with self.data.
            self.backups.append(self._copy_alive(self.data, timestamp))
            return len(self.backups)
    
        def restore(self, timestamp: int, backup_id: int) -> bool:
            # Guard backup_id < 1 explicitly so negative IDs do not index from the end of self.backups.
            if backup_id < 1 or backup_id > len(self.backups):
                return False
            # Copy again on restore so future writes mutate self.data without corrupting the stored snapshot.
            saved_snapshot = self.backups[backup_id - 1]
            self.data = self._copy_alive(saved_snapshot, timestamp)
            return True
    
    
    def run_in_memory_db(operations: List[str], arguments: List[List]) -> List:
        db = InMemoryDB()
        results: List[Any] = []
    
        # Replay each operation in timestamp order and collect its return value (None for set).
        for op, args in zip(operations, arguments):
            if op == "set":
                timestamp, key, field, value = args[0], args[1], args[2], args[3]
                ttl = args[4] if len(args) > 4 else 0
                db.set(timestamp, key, field, value, ttl)
                results.append(None)
            elif op == "get":
                timestamp, key, field = args[0], args[1], args[2]
                results.append(db.get(timestamp, key, field))
            elif op == "delete":
                timestamp, key, field = args[0], args[1], args[2]
                results.append(db.delete(timestamp, key, field))
            elif op == "backup":
                timestamp = args[0]
                results.append(db.backup(timestamp))
            elif op == "restore":
                timestamp, backup_id = args[0], args[1]
                results.append(db.restore(timestamp, backup_id))
            else:
                raise ValueError(f"Unknown operation: {op}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of this database as a filing cabinet of named folders (key), where each folder holds labeled sticky notes (field -> value). Some sticky notes have a time-to-live (TTL)—a lifespan after which the record automatically expires—so the moment we write a note at timestamp with a positive ttl, we stamp the exact "use before" deadline expire_at = timestamp + ttl right onto the note (or None if ttl == 0). Instead of running a background timer to throw away expired notes every second, we use lazy expiration, meaning we simply check whether timestamp < expire_at whenever someone reads, deletes, backs up, or restores a note.

Two naive shortcuts fail right away. First, if you store the duration ttl instead of the absolute deadline timestamp + ttl, you cannot tell whether a field has expired without also tracking when it was written, and restore easily miscalculates when restored records should die. Second, if backup saves self.data directly or uses a shallow copy (copying only the outer dictionary while sharing the inner {field: ...} dictionaries), any future set or delete silently mutates your saved backup—and the same corruption happens in reverse if restore points self.data directly at the stored snapshot without copying it again.

Walk through Example 1 on "acct:9" to see how absolute deadlines and two-level copies work together: 1. set(2, "acct:9", "token", "tk_alpha", ttl=8) stores ("tk_alpha", 10) inside self.data["acct:9"]["token"] (while "tier" stores ("pro", None)). 2. backup(6) copies all currently alive fields into backups[0] (backup_id = 1), preserving ("tk_alpha", 10) and ("pro", None). 3. set(7, "acct:9", "token", "tk_beta", ttl=0) and delete(8, "acct:9", "tier") mutate the live store, while backups[0] remains untouched. 4. restore(9, 1) copies alive entries from backups[0] back into self.data; since 9 < 10, get(9, "acct:9", "token") returns "tk_alpha". 5. At timestamp = 10, get(10, "acct:9", "token") sees 10 >= 10 and returns None, while permanent "tier" still returns "pro".

Complexity

Let F be the number of stored (key, field) entries in the database (at most 20,000) and B be the number of backups created (at most 100).

  • Time: set, get, and delete each take O(1) average time because they perform at most two hash-map lookups and a constant-time timestamp comparison. backup and restore each take O(F) time because _copy_alive visits every stored field in the source dictionary to copy the ones that are still alive; across at most 100 backup/restore calls on at most 20,000 fields, that is at most 2,000,000 simple dictionary insertions total.
  • Space: O(F) for the live self.data dictionary plus the sum of alive field counts across all snapshots, which is at most O(B * F). Each snapshot allocates its own outer and inner dictionaries, while safely sharing the immutable (value, expire_at) tuples.

Edge cases

  • Exact expiration boundary (timestamp == expire_at): After set(2, "acct:9", "token", "tk_alpha", ttl=8), expire_at is 10, so the field is still readable at 9 (9 < 10) and expired at 10 (10 >= 10).
  • Permanent fields (ttl == 0 or omitted ttl): expire_at is None, so the field never expires even at timestamp = 10^9.
  • Overwriting an existing field: Calling set with ttl=0 clears an existing expiration deadline; calling set with ttl > 0 sets a brand-new deadline timestamp + ttl.
  • delete on an expired field: Must return False because the field was already dead at timestamp, and subsequent get calls must continue returning None.
  • delete on one field among many: Removes only that field under key, leaving sibling fields untouched.
  • Invalid backup_id (<= 0 or > len(backups)): Must return False without modifying live state; checking backup_id < 1 prevents 0 or -1 from indexing from the back of Python's self.backups list.
  • Restoring the same backup_id multiple times: Mutations made after the first restore must not leak into the saved snapshot, so a second restore of the same ID restores the exact original state again.
  • Restoring after a captured field has expired: A field that was alive at backup(2) with expire_at = 11 is skipped when restore(20, 1) runs at timestamp = 20.

Common mistakes

  • Off-by-one check (timestamp <= expire_at instead of timestamp < expire_at): Keeps expired fields alive for one extra tick, causing get(10, "acct:9", "token") in Example 1 to return "tk_alpha" instead of None.
  • Shallow-copying self.data in backup: Writing dict(self.data) or self.data.copy() shares the inner field dictionaries between live state and the snapshot, so later set/delete calls corrupt the backup.
  • Assigning by reference in restore: Writing self.data = self.backups[backup_id - 1] without copying means subsequent writes mutate the stored snapshot in place.
  • Forgetting backup_id < 1: In Python, self.backups[0 - 1] evaluates self.backups[-1] and silently restores the latest backup instead of returning False.
  • Rebasing TTL on restore: Recomputing timestamp + remaining_ttl during restore implements relative TTL rather than keeping original absolute expiration times.

Follow-up questions

  • If the store holds millions of keys and snapshots are taken every few seconds, how can you avoid cloning the entire dataset on each backup? Instead of copying every key on every backup, use copy-on-write (CoW)—a technique where two versions share the same memory until one of them modifies it. On backup, copy only the outer key -> fields dictionary references (or increment a reference count) and mark the inner fields dictionaries as shared; when set or delete later touches a shared key, clone only that single key's inner dictionary before mutating it. For even larger scale, a persistent hash array mapped trie (HAMT)—a tree-shaped immutable map that shares unchanged subtrees across versions—makes backup O(1) and set/get O(log N) with minimal memory overhead.
  • Suppose restoring a snapshot should pause and resume each field's remaining lifespan instead of keeping its fixed wall-clock deadline; what would change? During backup(backup_ts), instead of saving expire_at directly, store the remaining lifespan remaining = expire_at - backup_ts (or None when expire_at is None). Because backup only captures alive fields (backup_ts < expire_at), remaining is guaranteed to be at least 1. Then during restore(restore_ts, backup_id), reconstruct each field's new deadline as restore_ts + remaining (or None), giving the field the exact remaining time it had when the snapshot was taken.
  • How would you proactively purge expired entries to free RAM when dead keys are never queried again? Maintain a min-heap—a binary tree stored in a list that always keeps the smallest element at index 0—containing (expire_at, key, field) tuples pushed on every set with ttl > 0. At the beginning of each operation (or on a periodic tick), pop all heap entries with expire_at <= timestamp and delete (key, field) from self.data only if its currently stored expire_at still matches the popped timestamp (ignoring stale heap entries left behind by earlier overwrites or deletes, a trick called lazy heap deletion). Each set pushes at most one tuple and each tuple is popped at most once in O(log F) time, while restore simply rebuilds the heap from the restored alive fields.

Follow-up questions

Similar questions

More Anthropic interview questions

All 254 Anthropic questions →