Simulate Key-Value Operations
Arrays & HashingAuto-graded · 17 test casesLast updated
Process a series of insertion, update, and deletion instructions on a key-value store and return the final contents ordered by key.
You are tasked with maintaining a simple key-value store that supports three types of sequential modifications:
["INSERT", key, value]: Addskeywith its correspondingvalueto the store. Ifkeyis already present in the store, this command is skipped.["UPDATE", key, value]: Modifies the value of an existingkeytovalue. Ifkeyis not currently in the store, this command is skipped.["REMOVE", key]: Deleteskeyand its value from the store. Ifkeydoes not exist in the store, this command is skipped.
Beginning with an empty key-value store, execute all instructions in the given order. Return the resulting state of the store as a list of [key, value] pairs, sorted lexicographically by key.
Constraints
1 <= len(operations) <= 10^51 <= len(key), len(value) <= 50keyandvalueconsist only of alphanumeric characters ([a-zA-Z0-9]).- Each command is validly formatted as one of
["INSERT", key, value],["UPDATE", key, value], or["REMOVE", key].
Examples
Example 1
Input: process_store_operations([['INSERT', 'apple', '10'], ['INSERT', 'banana', '20'], ['UPDATE', 'apple', '15'], ['INSERT', 'apple', '30'], ['REMOVE', 'banana'], ['UPDATE', 'orange', '5'], ['INSERT', 'cherry', '25']])
Output: [['apple', '15'], ['cherry', '25']]
Example 2
Input: process_store_operations([['REMOVE', 'missing_key'], ['INSERT', 'k1', 'v1'], ['REMOVE', 'k1'], ['UPDATE', 'k1', 'v2']])
Output: []
Hints
Hint 1
Use a hash table (dictionary) to track the current state of each key with O(1) lookup and modification times.
Hint 2
Pay close attention to the conditions: INSERT does nothing if the key already exists, while UPDATE does nothing if the key is missing.
Hint 3
Instead of maintaining order after every command, sort the keys once after processing all instructions.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We can simulate the key-value store using a hash dictionary to allow average $O(1)$ lookups, insertions, and deletions per command.
We iterate through the list of commands sequentially and enforce the specific guard conditions for each command type:
INSERT: Check ifkeyis in our dictionary. If absent, setstore[key] = value. If present, ignore.UPDATE: Check ifkeyis in our dictionary. If present, updatestore[key] = value. If absent, ignore.REMOVE: Safely removekeyfrom our dictionary if present (e.g. usingstore.pop(key, None)).
After executing all instructions, we extract the remaining keys, sort them in standard lexicographical order, and build the resulting list of [key, value] pairs.
Complexity
- Time Complexity:
- Processing $N$ operations takes $O(N \cdot L)$ time, where $L$ is the max string length (since hashing a string of length $L$ takes $O(L)$ time).
- If $K$ keys remain at the end ($K \le N$), sorting them takes $O(K \log K \cdot L)$ time.
- Overall time complexity is $O(N \cdot L + K \log K \cdot L)$, which runs well within time limits for $N = 10^5$.
- Space Complexity: $O(K \cdot L)$ to store up to $K$ active key-value pairs in the dictionary and construct the final output.
from typing import List
def process_store_operations(operations: List[List[str]]) -> List[List[str]]:
store = {}
for op in operations:
cmd = op[0]
key = op[1]
if cmd == "INSERT":
if key not in store:
store[key] = op[2]
elif cmd == "UPDATE":
if key in store:
store[key] = op[2]
elif cmd == "REMOVE":
store.pop(key, None)
return [[k, store[k]] for k in sorted(store.keys())]