Replay Guarded Key-Value Store Commands

Easy · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Design a command processor process_store_operations(operations) that starts with an empty in-memory string table and executes a sequence of instructions in arrival order. Each entry in operations is a list of strings matching one of three instruction formats:

  • ["INSERT", key, value] — Creates a new mapping from key to value only if key is not currently stored; if key is already present, leave its existing value untouched.
  • ["UPDATE", key, value] — Replaces the value mapped to key with value only if key is currently stored; if key is absent, do nothing.
  • ["REMOVE", key] — Deletes key and its value only if key is currently stored; if key is absent, do nothing.

Once every instruction has been processed, return all surviving entries as two-element [key, value] lists ordered by key in ascending lexicographical (ASCII character-code) order.

Examples

Example 1

operations = [
    ["INSERT", "hostB", "8080"],
    ["INSERT", "hostA", "3000"],
    ["UPDATE", "hostB", "9090"],
    ["INSERT", "hostB", "7070"],
    ["UPDATE", "hostC", "5000"],
    ["REMOVE", "hostA"],
    ["INSERT", "hostD", "4000"],
]
# Output: [["hostB", "9090"], ["hostD", "4000"]]

Walk-through: "hostB" is created with "8080" and updated to "9090"; the second "INSERT" on "hostB" is skipped because "hostB" already exists. "hostA" is created and later deleted. Updating "hostC" is skipped because "hostC" was never added, and "hostD" is created with "4000". Sorting the remaining keys gives [["hostB", "9090"], ["hostD", "4000"]].

Example 2

operations = [
    ["UPDATE", "job1", "queued"],
    ["INSERT", "job1", "running"],
    ["REMOVE", "job9"],
    ["REMOVE", "job1"],
    ["UPDATE", "job1", "done"],
]
# Output: []

Walk-through: The first "UPDATE" on "job1" is ignored because "job1" has not been inserted yet. "job1" is then inserted as "running", removing absent "job9" has no effect, "job1" is deleted, and the final "UPDATE" on "job1" is ignored because "job1" is gone again, leaving [].

Constraints

  • 1 <= len(operations) <= 10^5
  • 1 <= len(key), len(value) <= 50
  • Every key and value contains only ASCII letters and digits (a-z, A-Z, 0-9).
  • Every command is well-formed as ["INSERT", key, value], ["UPDATE", key, value], or ["REMOVE", key].

Step-by-step walkthrough

  1. Understand the commands and their guard rules

    We start with an empty string-to-string table and execute each instruction in order. Every mutation depends on whether key currently exists in the table:

    Instruction When key IS present When key is NOT present
    ["INSERT", key, value] Do nothing (preserve current value) Store key -> value
    ["UPDATE", key, value] Replace current value with value Do nothing (do not create key)
    ["REMOVE", key] Delete key from the table Do nothing

    Pay special attention to three subtleties:

    • INSERT is create-only, not an overwrite: once "hostB" holds "9090", ["INSERT", "hostB", "7070"] leaves "9090" intact.
    • UPDATE is modify-only, not an upsert (update-or-insert): when "hostC" is absent, ["UPDATE", "hostC", "5000"] does not create "hostC".
    • Deleting a key returns it to the absent state, so a later UPDATE on that key is skipped whereas a later INSERT succeeds.

    Once every instruction has run, we emit all surviving [key, value] pairs sorted in ascending lexicographical order (character-by-character ASCII order) by key.

  2. Why a hash map beats a plain or sorted list

    Storing [key, value] pairs in a plain Python list forces a linear scan on every instruction to check whether key exists. Across 100,000 commands—for example, 50,000 distinct inserts followed by 50,000 updates—each update scans up to 50,000 entries, burning ~2.5 * 10^9 string comparisons. Keeping a sorted list via binary search avoids slow lookups, yet still shifts up to 50,000 items in memory on every insert or delete.

    A hash map (Python's dict) jumps directly to a key's bucket in O(1) average time. Because sorted order is only required once when building the return value, we skip all intermediate sorting and sort the surviving keys a single time at the end.

  3. Execute each command safely

    Notice that INSERT and UPDATE carry three strings ([command, key, value]), while REMOVE carries only two ([command, key]). Read command = op[0] and key = op[1] first, and touch op[2] only inside INSERT and UPDATE.

    Guarding every branch with key not in store or key in store enforces the command rules directly and prevents del store[key] from ever raising a KeyError:

    def process_store_operations(operations: List[List[str]]) -> List[List[str]]:
        # store: hash map {key: current_value}, e.g. {"hostB": "9090", "hostD": "4000"}
        store: Dict[str, str] = {}
    
        # Phase 1: replay every command in order, checking key presence before mutating.
        for op in operations:
            command = op[0]
            key = op[1]
    
            if command == "INSERT":
                # INSERT creates a new entry only; duplicate inserts must leave the old value intact.
                if key not in store:
                    store[key] = op[2]
            elif command == "UPDATE":
                # UPDATE modifies an existing entry only; missing keys must not be created.
                if key in store:
                    store[key] = op[2]
            elif command == "REMOVE":
                # REMOVE has only 2 items [command, key]; check presence before deleting to avoid KeyError.
                if key in store:
                    del store[key]
            else:
                raise ValueError(f"unknown command: {command}")
    
        return []
    
  4. Sort surviving keys once at the end

    Python dictionaries iterate in insertion order, not alphabetical order—for example, inserting "hostD" before "hostB" would list "hostD" first unless we sort.

    Calling sorted(store.keys()) orders keys by ASCII code points ('0'-'9' < 'A'-'Z' < 'a'-'z'; "a10" precedes "a2" because '1' < '2'). Wrapping each entry in a two-item list [key, store[key]] matches the List[List[str]] return signature:

        # Phase 2: sort surviving keys in ascending lexicographical order once at the end.
        result: List[List[str]] = []
        for key in sorted(store.keys()):
            result.append([key, store[key]])
    
  5. Trace Example 1 step by step

    Let's follow store across all seven instructions in Example 1:

    Step  Instruction                    Key check        Action                store after step
    ----  -----------------------------  ---------------  --------------------  ------------------------------------
    1     ["INSERT", "hostB", "8080"]    "hostB" absent   set "hostB" = "8080"  {"hostB": "8080"}
    2     ["INSERT", "hostA", "3000"]    "hostA" absent   set "hostA" = "3000"  {"hostB": "8080", "hostA": "3000"}
    3     ["UPDATE", "hostB", "9090"]    "hostB" present  set "hostB" = "9090"  {"hostB": "9090", "hostA": "3000"}
    4     ["INSERT", "hostB", "7070"]    "hostB" present  ignored               {"hostB": "9090", "hostA": "3000"}
    5     ["UPDATE", "hostC", "5000"]    "hostC" absent   ignored               {"hostB": "9090", "hostA": "3000"}
    6     ["REMOVE", "hostA"]            "hostA" present  delete "hostA"        {"hostB": "9090"}
    7     ["INSERT", "hostD", "4000"]    "hostD" absent   set "hostD" = "4000"  {"hostB": "9090", "hostD": "4000"}
    
    Final sort: sorted(["hostB", "hostD"]) -> ["hostB", "hostD"]
    Output:     [["hostB", "9090"], ["hostD", "4000"]]
    
  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def process_store_operations(operations: List[List[str]]) -> List[List[str]]:
        # store: hash map {key: current_value}, e.g. {"hostB": "9090", "hostD": "4000"}
        store: Dict[str, str] = {}
    
        # Phase 1: replay every command in order, checking key presence before mutating.
        for op in operations:
            command = op[0]
            key = op[1]
    
            if command == "INSERT":
                # INSERT creates a new entry only; duplicate inserts must leave the old value intact.
                if key not in store:
                    store[key] = op[2]
            elif command == "UPDATE":
                # UPDATE modifies an existing entry only; missing keys must not be created.
                if key in store:
                    store[key] = op[2]
            elif command == "REMOVE":
                # REMOVE has only 2 items [command, key]; check presence before deleting to avoid KeyError.
                if key in store:
                    del store[key]
            else:
                raise ValueError(f"unknown command: {command}")
    
        # Phase 2: sort surviving keys in ascending lexicographical order once at the end.
        result: List[List[str]] = []
        for key in sorted(store.keys()):
            result.append([key, store[key]])
        return result
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture labeled lockers along a wall where each locker tag (key) can hold one note card (value). Every instruction enforces a strict guard: INSERT places a card only into an empty locker (leaving occupied lockers alone), UPDATE swaps the card only inside an occupied locker (ignoring empty ones), and REMOVE clears an occupied locker. Backed by a hash map (Python's dict, which hashes each key string into a bucket index so lookups, insertions, and deletions run in constant average time), we jump straight to the target locker on each step instead of walking down the wall.

Storing [key, value] pairs in an unsorted list would scan up to n items on every command, turning 100,000 instructions into billions of comparisons. Keeping a list sorted at all times (bisect.insort / list.pop) still shifts thousands of elements on every insert or removal, even though callers only ask for sorted order once after the final command. Mutating an O(1) hash map during execution and sorting the surviving keys once at the end gives the best of both worlds.

Trace five quick steps to see every guard rule in action:

  1. ["INSERT", "hostB", "8080"]: "hostB" is absent, so store becomes {"hostB": "8080"}.
  2. ["INSERT", "hostA", "3000"]: "hostA" is absent, so store becomes {"hostB": "8080", "hostA": "3000"}.
  3. ["INSERT", "hostB", "7070"]: "hostB" is already present, so this duplicate insert is ignored and "hostB" keeps "8080".
  4. ["UPDATE", "hostC", "5000"]: "hostC" is absent, so this update is ignored rather than creating "hostC".
  5. Sorting store's keys yields ["hostA", "hostB"], returning [["hostA", "3000"], ["hostB", "8080"]].

Complexity

Let n be len(operations), m be the number of keys remaining at the end (m <= n), and L <= 50 be the maximum string length of any key or value:

  • Time — O(n * L + m log m * L) average (effectively O(n + m log m) since L <= 50): Replaying n commands performs one hash lookup and at most one dictionary write or delete per command, touching up to L characters per key (O(L) average). Sorting the m remaining keys performs O(m log m) comparisons of up to L-character strings, followed by a single O(m) pass to build the output pairs.
  • Space — O(p * L) where p <= n is the peak number of keys stored simultaneously: The hash map holds at most p entries at once (note p can exceed m when many keys are inserted and later removed, as in Example 2), and the output list uses O(m * L) space.

Edge cases

  • Duplicate INSERT on an active key: Ignored; the existing value (whether from the original INSERT or a later UPDATE) stays unchanged.
  • UPDATE or REMOVE on a never-inserted key: Quietly skipped without raising an error or creating a key.
  • UPDATE after REMOVE: Deleting a key makes it absent again, so a subsequent UPDATE on it is ignored (as on "job1" at the end of Example 2).
  • Re-inserting after REMOVE: Because del store[key] removes the entry completely, a later INSERT on the same key succeeds with the new value.
  • Empty store at completion: When every inserted key is eventually removed, sorted(store.keys()) is [] and the function returns [].
  • ASCII code-point ordering: Standard lexicographical sorting compares character codes ('0'-'9' < 'A'-'Z' < 'a'-'z'), placing "1" before "B" before "a10" before "a2" before "b".

Common mistakes

  • Assigning store[key] = op[2] unconditionally on INSERT: Standard dictionary assignment overwrites existing keys, breaking the rule that duplicate inserts must be ignored (which would turn "hostB" into "7070" instead of "9090" in Example 1).
  • Assigning store[key] = op[2] unconditionally on UPDATE: Without if key in store:, UPDATE inserts missing keys instead of skipping them.
  • Unpacking three variables (cmd, key, val = op) unconditionally: REMOVE entries have length 2 (["REMOVE", key]), so 3-way unpacking raises ValueError.
  • Calling del store[key] without a membership check: Deleting a missing key raises KeyError; always check if key in store: (or use store.pop(key, None)).
  • Relying on Python dict iteration order: Python dictionaries preserve insertion order, not lexicographical key order.
  • Returning sorted(store.items()) directly: dict.items() yields (key, value) tuples rather than two-element [key, value] lists.

Alternative approaches

  • Ordered map / balanced search tree: Keeping entries inside a balanced binary search tree (a self-adjusting tree that keeps keys ordered at shallow depth) runs each INSERT, UPDATE, and REMOVE in O(log p) time and reads off sorted keys in O(m) time at the end. When sorted order is requested only once at completion, an O(1) hash map plus one final sort is faster and simpler.
  • Stable sort by key: Because commands on distinct keys never interact, stably sorting all commands by key (O(n log n)) groups each key's command history together in chronological order so each key's final state can be folded in a single scan without a hash table.

Follow-up questions

  • How would you extend the store so a multi-command transaction either commits as a unit or rolls back cleanly on error? Record an undo log—a list of (key, previous_value) entries (using None when key did not exist before)—for every command in the transaction that actually mutates store. Ignored commands change nothing and log nothing; if an error aborts the transaction, walk the undo log backward to restore every modified key to its pre-transaction state, or discard the undo log upon commit. If durability across process crashes is also required, append the batch and a commit record to a write-ahead log (WAL)—an append-only disk file flushed before acknowledging commits—and replay only committed transactions on recovery.
  • What underlying structure would replace the hash table if callers interleaved frequent sorted range scans with mutations? Swap the hash map for an ordered map such as a balanced binary search tree (std::map in C++, TreeMap in Java), a B-tree (a cache-friendly tree packing dozens of sorted keys per node), or a skip list (a multi-level linked list with express pointers that skip across many nodes). Individual INSERT, UPDATE, and REMOVE calls take O(log n) time instead of O(1) average, while full ordered iteration or [low_key, high_key] range queries run in O(log n + k) time for k matched keys rather than O(n log n) per query. In Python, third-party sortedcontainers.SortedDict offers fast B-tree-like performance when standard-library constraints are lifted.
  • How could you process commands across multiple worker threads while preserving a single sequentially consistent execution order? Sequential consistency requires the concurrent store to behave as if all operations executed one at a time along a single global timeline that preserves each client thread's submission order. Because every command touches only one key, operations on different keys commute once their global arrival order is assigned: place a lightweight sequencer (or single ring buffer) in front that assigns monotonic sequence numbers and partitions commands by hash(key) % num_shards into per-shard queues owned by dedicated worker threads. Each shard mutates its own private dictionary with zero lock contention while preserving per-key order; for a full sorted snapshot, either briefly quiesce the sequencer while k-way merging shard outputs, or keep multi-version (sequence_id, value) histories per key so readers read a consistent cut at sequence S. Note that standard CPython's Global Interpreter Lock (GIL)—a mutex allowing only one thread to execute Python bytecode at once—serializes CPU-bound threads, so true multi-core throughput requires multiprocessing, free-threaded Python, or a systems language such as Rust, C++, or Go.

Follow-up questions

Similar questions

More Squarepoint interview questions

All 38 Squarepoint questions →