Snapshot-based key-value store with checkpoint and reload
Data Structure DesignAuto-graded · 14 test casesLast updated
Simulate a key-value store that serializes its full contents on checkpoint and replaces live state on reload, testing state management and round-trip serialization.
Snapshot-Based Key-Value Store
You are building an in-memory key-value store that can save its contents to a simulated durable medium and later reload them. You will receive a sequence of commands and must return the result of each one.
The store supports four commands:
setwith arguments[key, value]: storevalueunderkey, overwriting any previous value. ReturnsNone.getwith arguments[key]: return the value stored underkey, orNoneif the key is absent. Does not modify state.shutdownwith no arguments: serialize the entire current contents of the store into bytes (for example, UTF-8 encoded JSON) and write those bytes to the medium, replacing any earlier snapshot. The live in-memory data is not cleared, so latergetcalls still see it. ReturnsNone.restorewith no arguments: discard the live in-memory data and rebuild it from the medium's most recent snapshot. If no snapshot has ever been written, the store becomes empty. ReturnsNone.
Behavior details to honor:
- Writes made after the last
shutdownare lost whenrestoreruns, becauserestorereplaces the live data entirely. - Only the most recent
shutdownsnapshot is kept. Earlier snapshots are overwritten. - Keys are strings. Values are JSON-compatible (strings or integers in the tests).
- If a command name is not one of the four above, raise
ValueError.
Implement the function so that it processes the commands in order and returns a list with one result per command.
Input
commands: a list of command names.params: a list of argument lists, whereparams[i]holds the arguments forcommands[i].
Output
A list of the same length as commands. Each entry is the result of the corresponding command: None for set, shutdown, and restore, and the looked-up value (or None) for get.
Constraints
0 <= len(commands) == len(params) <= 10^5- Each
commands[i]is one of"set","get","shutdown","restore", or an unknown string that must triggerValueError. - For
set,params[i]has exactly two elements: a string key and a JSON-compatible value. - For
get,params[i]has exactly one element: a string key. - For
shutdownandrestore,params[i]is an empty list. - The total size of all stored keys and values is bounded so that a full snapshot fits in memory.
Examples
Example 1
Input: run_snapshot_store(['set', 'get', 'shutdown', 'set', 'get', 'restore', 'get'], [['name', 'Ada'], ['name'], [], ['name', 'Grace'], ['name'], [], ['name']])
Output: [None, 'Ada', None, None, 'Grace', None, 'Ada']
Example 2
Input: run_snapshot_store(['get', 'restore', 'get', 'set', 'shutdown', 'set', 'restore', 'get'], [['missing'], [], ['missing'], ['x', 7], [], ['x', 9], [], ['x']])
Output: [None, None, None, None, None, None, None, 7]
Hints
Hint 1
Keep two things separately: the live dictionary that `set` and `get` act on, and a stored snapshot that only `shutdown` writes and only `restore` reads.
Hint 2
Because `restore` replaces the live data, a snapshot must be an independent copy. Storing a serialized form (for example, JSON bytes) guarantees that later `set` calls cannot change it.
Hint 3
Handle `restore` before any `shutdown` by resetting to an empty dictionary, and make sure `get` returns `None` for missing keys rather than raising.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Track two pieces of state. The first is a live dictionary, live, which handles set and get in constant average time. The second is snapshot, which holds the serialized bytes from the most recent shutdown, or None if no shutdown has happened yet.
- On
shutdown, serialize the live dictionary into bytes and store them as the snapshot. Serializing creates a frozen copy, so later changes tolivedo not affect it. - On
restore, decode the snapshot and build a fresh dictionary from it. If there is no snapshot, the store becomes empty. - On
get, usedict.getso missing keys returnNone. - Any other command name raises
ValueError.
Why It Is Correct
- Snapshot isolation: the bytes are built at shutdown time and never change afterward, so writes made after a shutdown cannot leak into a later restore. This matches the required behavior that unflushed writes disappear.
- Lossless round trip: JSON encoding with string keys and JSON-compatible values decodes back to an equal dictionary. Escaping inside JSON ensures that special characters in keys or values cannot be confused with structural syntax.
- Full replacement on restore: the decoded dictionary is a new object, so the state after restore depends only on the last snapshot.
- Shutdown does not wipe memory:
shutdownwrites the snapshot but leaveslivealone, so subsequentgetcalls see the current data.
Complexity
Let N be the total size of all stored keys and values, and K the number of keys.
setandget: O(1) average time per call, excluding hashing cost.shutdown: O(N + K log K) time because of serialization and the sorted key order, and O(N) space for the snapshot bytes.restore: O(N) time and space to parse and rebuild the dictionary.- Overall: O(N) space for the live data plus the snapshot.
Reference Solution
import json
from typing import Any, List
def run_snapshot_store(commands: List[str], params: List[List[Any]]) -> List[Any]:
live = {}
snapshot = None # serialized bytes of the last shutdown, or None
output = []
for command, args in zip(commands, params):
if command == "set":
key, value = args
live[key] = value
output.append(None)
elif command == "get":
output.append(live.get(args[0]))
elif command == "shutdown":
snapshot = json.dumps(
live, sort_keys=True, separators=(",", ":"), ensure_ascii=False
).encode("utf-8")
output.append(None)
elif command == "restore":
live = json.loads(snapshot.decode("utf-8")) if snapshot is not None else {}
output.append(None)
else:
raise ValueError("unknown operation")
return output