Simulate an In-Memory Key-Value Store
Data Structure DesignAuto-graded · 15 test casesLast updated
Tests ability to implement a command-driven key-value store with correct upsert, lookup, conditional update, delete, and membership semantics.
Problem
You are given a sequence of operations to run against an in-memory key-value store, starting empty. Each operation is a string, and each comes with a list of arguments. Process every operation in order and collect the return value of each one into a result list.
The store supports five operations:
put(key, value)
Insert or overwrite the entry for key with value. Always returns None.
get(key)
Return the value stored under key, or None if the key does not exist.
update(key, value)
If key exists, replace its value with value and return True. If the key does not exist, do nothing and return False.
delete(key)
If key exists, remove it and return True. If it does not exist, return False.
exists(key)
Return True if key is currently in the store, False otherwise.
Return the list of results, one per operation, in the same order.
Constraints
1 <= len(operations) == len(arguments) <= 1000- Every string in
operationsis one of:"put","get","update","delete","exists". - Keys are strings. Values may be any JSON-serializable type.
putandupdatereceive two arguments;get,delete, andexistsreceive one.putis the only operation that can create a new key.updatemust not create keys.- A key deleted by
deleteis fully gone; subsequentgetreturnsNoneandexistsreturnsFalse. - The store begins empty before the first operation.
Examples
Example 1
Input: run_kv_store(['put', 'get', 'exists', 'update', 'get', 'delete', 'get'], [['a', 1], ['a'], ['a'], ['a', 2], ['a'], ['a'], ['a']])
Output: [None, 1, True, True, 2, True, None]
Example 2
Input: run_kv_store(['put', 'put', 'get'], [['x', 'old'], ['x', 'new'], ['x']])
Output: [None, None, 'new']
Example 3
Input: run_kv_store(['get', 'update', 'delete', 'exists'], [['missing', ['v']], ['missing', 3], ['missing'], ['missing']])
Output: [None, False, False, False]
Hints
Hint 1
A plain dictionary is all the storage you need — every required operation maps directly to a dict method or membership test.
Hint 2
Distinguish `put` from `update` carefully: `put` is an unconditional upsert that always returns `None`, while `update` is a conditional write that returns a boolean and must never create a key.
Hint 3
Walk through a case where a key is put, then deleted, then read or updated — make sure your code returns the right values at each step rather than carrying stale state.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A Python dict handles every operation directly. The whole challenge is getting the contract right for each command — especially the difference between put and update, and the return value of each.
Walk through the contract once before coding:
| Operation | Key present | Key absent | Returns |
|---|---|---|---|
put(k, v) | overwrites | creates | None always |
get(k) | returns value | — | value or None |
update(k, v) | replaces value | no-op | True / False |
delete(k) | removes key | no-op | True / False |
exists(k) | — | — | True / False |
The key distinction: put is an unconditional upsert — it never fails and never returns a boolean. update is a conditional write — it refuses to create new keys and signals success or failure via its return value. Mixing these two up is the most common error.
The loop pairs each operation string with its argument list using zip, dispatches on the operation name, and appends exactly one value to results per iteration. After all operations are processed, results is returned.
Why it is correct:
store.get(key)returnsNonefor missing keys, matching the specifiedgetbehavior without any explicit membership check.updateanddeleteboth guard withkey in storebefore touching the dictionary, so they can never create entries and are both idempotent on missing keys.putassigns unconditionally, so it handles both the create and overwrite cases with a single line.- Every branch appends exactly one value, so
len(results) == len(operations)is guaranteed.
Edge cases:
geton a never-inserted or previously-deleted key returnsNone.updateafterdeletereturnsFalse— the key is gone, so the guard fails.puton an already-existing key silently overwrites; subsequentgetsees the new value.deletecalled twice on the same key: first call returnsTrue, second returnsFalse.
Complexity:
- Time: O(1) average per operation (hash table lookup/insert/delete). O(n) overall for n operations.
- Space: O(k) where k is the number of distinct keys currently held in the store, bounded by n.
from typing import List
def run_kv_store(operations: List[str], arguments: List[List[object]]) -> List[object]:
store = {}
results = []
for operation, args in zip(operations, arguments):
if operation == "put":
key, value = args
store[key] = value
results.append(None)
elif operation == "get":
key = args[0]
results.append(store.get(key))
elif operation == "update":
key, value = args
if key in store:
store[key] = value
results.append(True)
else:
results.append(False)
elif operation == "delete":
key = args[0]
if key in store:
del store[key]
results.append(True)
else:
results.append(False)
elif operation == "exists":
results.append(args[0] in store)
else:
raise ValueError(f"Unknown operation: {operation}")
return results