Execute In-Memory Key-Value Storage Commands
Arrays & HashingAuto-graded · 19 test casesLast updated
Simulate an in-memory key-value dictionary given a sequence of insertion, lookup, and deletion instructions.
You are tasking with implementing the execution engine for an in-memory key-value database. The system processes a sequence of instructions sequentially.
Each instruction in the list operations is formatted as one of the following command lists:
["SET", "key", "value"]: Storesvaluecorresponding tokey. Ifkeyalready exists, update its value.["GET", "key"]: Retrieves the current value mapped tokey. Ifkeydoes not currently exist in the store, output"null".["DELETE", "key"]: Removeskeyand its assigned value. Ifkeyis not present, no change occurs.
Write a function process_operations(operations) that executes all input actions in order and returns a list containing the output of every GET instruction encountered.
Constraints
- $1 \le \text{len(operations)} \le 10^5$
- Each operation is a list of strings: 2 items for
GETandDELETE, 3 items forSET. - All keys and values are non-empty strings containing only alphanumeric characters.
Examples
Example 1
Input: process_operations([['SET', 'a', '1'], ['GET', 'a'], ['DELETE', 'a'], ['GET', 'a']])
Output: ['1', 'null']
Example 2
Input: process_operations([['SET', 'x', '10'], ['SET', 'x', '20'], ['GET', 'x']])
Output: ['20']
Hints
Hint 1
Use a standard hash table / dictionary to track active key-value pairs.
Hint 2
Ensure deleting a non-existent key does not raise an exception.
Hint 3
Only record outputs into the result list when processing a 'GET' command.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We can maintain the internal state of the key-value store using a standard hash map (Python dict).
Iterate through the operations sequence step by step:
SET: Assignstore[key] = value. This handles both new insertions and updating existing keys.GET: Checkstoreforkey. If present, appendstore[key]to our results array; otherwise, append the string"null". Usingdict.get(key, "null")performs this cleanly.DELETE: Removekeyusingstore.pop(key, None). Providing a default value prevents raising a key error if the entry is missing.
Complexity Analysis
- Time Complexity: $O(N)$ overall, where $N$ is the total number of operations. Each dictionary operation (
SET,GET,DELETE) operates in $O(1)$ average time. - Space Complexity: $O(U + G)$ where $U$ is the number of distinct active keys stored simultaneously and $G$ is the total number of
GETcommands processed. Both are bounded by $O(N)$.
Python Solution
from typing import List
def process_operations(operations: List[List[str]]) -> List[str]:
store = {}
output = []
for op in operations:
action = op[0]
key = op[1]
if action == "SET":
store[key] = op[2]
elif action == "GET":
output.append(store.get(key, "null"))
elif action == "DELETE":
store.pop(key, None)
return output