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 fromkeytovalueonly ifkeyis not currently stored; ifkeyis already present, leave its existing value untouched.["UPDATE", key, value]— Replaces the value mapped tokeywithvalueonly ifkeyis currently stored; ifkeyis absent, do nothing.["REMOVE", key]— Deleteskeyand its value only ifkeyis currently stored; ifkeyis 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^51 <= len(key), len(value) <= 50- Every
keyandvaluecontains 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
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
keycurrently exists in the table:Instruction When keyIS presentWhen keyis NOT present["INSERT", key, value]Do nothing (preserve current value) Store key -> value["UPDATE", key, value]Replace current value with valueDo nothing (do not create key)["REMOVE", key]Delete keyfrom the tableDo nothing Pay special attention to three subtleties:
INSERTis create-only, not an overwrite: once"hostB"holds"9090",["INSERT", "hostB", "7070"]leaves"9090"intact.UPDATEis 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
UPDATEon that key is skipped whereas a laterINSERTsucceeds.
Once every instruction has run, we emit all surviving
[key, value]pairs sorted in ascending lexicographical order (character-by-character ASCII order) bykey.Why a hash map beats a plain or sorted list
Storing
[key, value]pairs in a plain Pythonlistforces a linear scan on every instruction to check whetherkeyexists. Across100,000commands—for example,50,000distinct inserts followed by50,000updates—each update scans up to50,000entries, burning ~2.5 * 10^9string comparisons. Keeping a sorted list via binary search avoids slow lookups, yet still shifts up to50,000items in memory on every insert or delete.A hash map (Python's
dict) jumps directly to a key's bucket inO(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.Execute each command safely
Notice that
INSERTandUPDATEcarry three strings ([command, key, value]), whileREMOVEcarries only two ([command, key]). Readcommand = op[0]andkey = op[1]first, and touchop[2]only insideINSERTandUPDATE.Guarding every branch with
key not in storeorkey in storeenforces the command rules directly and preventsdel store[key]from ever raising aKeyError: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 []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 theList[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]])Trace Example 1 step by step
Let's follow
storeacross 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"]]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:
["INSERT", "hostB", "8080"]:"hostB"is absent, sostorebecomes{"hostB": "8080"}.["INSERT", "hostA", "3000"]:"hostA"is absent, sostorebecomes{"hostB": "8080", "hostA": "3000"}.["INSERT", "hostB", "7070"]:"hostB"is already present, so this duplicate insert is ignored and"hostB"keeps"8080".["UPDATE", "hostC", "5000"]:"hostC"is absent, so this update is ignored rather than creating"hostC".- 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 (effectivelyO(n + m log m)sinceL <= 50): Replayingncommands performs one hash lookup and at most one dictionary write or delete per command, touching up toLcharacters per key (O(L)average). Sorting themremaining keys performsO(m log m)comparisons of up toL-character strings, followed by a singleO(m)pass to build the output pairs. - Space —
O(p * L)wherep <= nis the peak number of keys stored simultaneously: The hash map holds at mostpentries at once (notepcan exceedmwhen many keys are inserted and later removed, as in Example 2), and the output list usesO(m * L)space.
Edge cases
- Duplicate
INSERTon an active key: Ignored; the existing value (whether from the originalINSERTor a laterUPDATE) stays unchanged. UPDATEorREMOVEon a never-inserted key: Quietly skipped without raising an error or creating a key.UPDATEafterREMOVE: Deleting a key makes it absent again, so a subsequentUPDATEon it is ignored (as on"job1"at the end of Example 2).- Re-inserting after
REMOVE: Becausedel store[key]removes the entry completely, a laterINSERTon 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 onINSERT: 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 onUPDATE: Withoutif key in store:,UPDATEinserts missing keys instead of skipping them. - Unpacking three variables (
cmd, key, val = op) unconditionally:REMOVEentries have length 2 (["REMOVE", key]), so 3-way unpacking raisesValueError. - Calling
del store[key]without a membership check: Deleting a missing key raisesKeyError; always checkif key in store:(or usestore.pop(key, None)). - Relying on Python
dictiteration 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, andREMOVEinO(log p)time and reads off sorted keys inO(m)time at the end. When sorted order is requested only once at completion, anO(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 (usingNonewhenkeydid not exist before)—for every command in the transaction that actually mutatesstore. 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::mapin C++,TreeMapin 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). IndividualINSERT,UPDATE, andREMOVEcalls takeO(log n)time instead ofO(1)average, while full ordered iteration or[low_key, high_key]range queries run inO(log n + k)time forkmatched keys rather thanO(n log n)per query. In Python, third-partysortedcontainers.SortedDictoffers 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_shardsinto 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 sequenceS. 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
- How would you extend the store so a multi-command transaction either commits as a unit or rolls back cleanly on error?
- What underlying structure would replace the hash table if callers interleaved frequent sorted range scans with mutations?
- How could you process commands across multiple worker threads while preserving a single sequentially consistent execution order?
Similar questions
- Maximum Drawdown in a Cumulative PnL Series
- Even-Product Triplets Under a Modulus
- Counting Staircase Sequences With Custom Jumps
- Equalizing an Array via All-Except-One Increments
- Cross-Array Target Sum in Two Sorted Lists
- Highest-Frequency Lowercase Letter with Alphabetical Tie-Break
More Squarepoint interview questions
- Maximum Revenue Under Stock-Indexed Pricing Medium
- Fixed-Buffer Circular Queue vs Linked-Node Storage Medium
- Contrasting Bonds, Common Stock, and Dividend Policy Medium Pro
- First-Drawer Win Probability With Tied-Rank Reshuffles Medium Pro
- Compile-Time Merging of C++ Index Sequences Medium Pro
- Safe Regular-File Counting Across Arbitrary Paths Medium Pro
- Even-Product Triplets Under a Modulus Medium Pro
- Counting Staircase Sequences With Custom Jumps Medium Pro
- Sorted Contiguous Container With Move Semantics Medium Pro
- OLS Market Beta From Paired Return Series Medium Pro