← Questions
Persistent key-value store with binary snapshots
0
I was asked this
No reports yet. Sign in to say where you were asked it.
Implement an in-memory key-value store whose whole state can be saved to, and restored from, a storage medium that holds a single binary blob.
You are given:
class Medium:
def save(self, blob: bytes) -> None: ...
def load(self) -> bytes | None: ... # None if nothing was saved yet
class InMemoryMedium(Medium): ... # a working implementation for tests
Implement PersistentKVStore(medium) with:
-
put(key: str, value: str) -> Noneinserts or overwrites. get(key: str) -> str | None-
delete(key: str) -> boolreturns whether the key existed. -
save() -> Nonewrites the entire current state to the medium as onebytesblob. -
restore() -> Nonereplaces the in-memory state with what the medium holds.
Rules:
- Keys and values are arbitrary strings: they may be empty and may contain any character, including
=,,,:, newlines, NUL and non-ASCII text. - Design your own byte format. Do not use
json,pickle, or similar libraries. - A store created on the same medium after a "restart" must see exactly the data from the last
save(). - If the blob is malformed or truncated,
restore()must raise and must not leave the store half-loaded.
Example 1
m = InMemoryMedium()
a = PersistentKVStore(m)
a.put("user:1", "Ada")
a.put("note", "line one\nline two")
a.save()
b = PersistentKVStore(m)
b.restore()
b.get("note") -> "line one\nline two"
b.get("user:2") -> None
Example 2
a.put("", "empty key is fine")
a.put("city", "Zürich")
a.save()
a.put("draft", "not saved")
a.restore()
a.get("") -> "empty key is fine"
a.get("draft") -> None
Expect follow-ups such as a medium with a maximum blob size, writing an append-only log instead of a full snapshot, and thread safety.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
