Lesson 4 of 5
Building in parts
Some rounds hand you a small build and add to it part by part. Write each part so the next one is a small change, not a rewrite; here a key-value store gains timestamps and deletion, and a second store gains transactions.
Build a key-value store as a class whose methods are the only code that touches its notebook
Answer "what did this key hold at second t?" with a sorted history per key and a binary search
Add deletion to a history by writing a marker value, without changing the search
Add transactions with an undo record that saves each key's value from before its first change
Extend one transaction to nested ones with a stack of undo records and the merge rule for commit
Your team keeps the status of each pipeline job in memory: load is "running", ship is "queued". A dict does that in one line. Then someone on call asks what the status of load was at second 7, before it was restarted. The dict holds only the latest value, so it cannot say. Then a third request: jobs can be deleted, but a question about the past must still get the old answer.
Some interview rounds are built exactly this way. The interviewer hands you a small task, and once it works, adds a requirement, then another. This is a multi-part build: one program that grows in parts, where each part keeps every rule of the parts before it. These rounds are reported to grade readable, modular code. Modular means split into small pieces with one job each, so a change touches one piece.
The skill is writing part 1 so that part 2 is a small change, not a rewrite. This lesson grows the job store in three parts, names the habits that kept each change small, then uses them on a second store that gains transactions.
Part 1: a store that works
What is the least code that answers part 1: set(key, value), and get(key) with the empty string for a key never written? A class around one dict. A reminder from the LRU cache lesson: a class bundles a notebook with the methods that use it, where a method is a function that belongs to the class. Every method receives the object as self, so a name stored on it, such as self.data, survives from one call to the next. Store() makes a new object and runs its __init__ method on it.
The trace below makes a store, writes load twice and ship once, then reads load and a key that was never written. It hides self: inside each method, self is the same object as store, which shows its data inside. Before you step through, guess what the first print shows.
class Store:def __init__(self):self.data = {}def set(self, key, value):self.data[key] = valuedef get(self, key):return self.data.get(key, "")store = Store()store.set("load", "queued")store.set("ship", "queued")store.set("load", "running")print(store.get("load"))print(store.get("join") == "")
(nothing printed yet)Code outside the class never touches store.data. It calls set and get, and only those two methods know that a dict sits inside. That rule is what keeps part 2 small: when the notebook has to change, the methods change and the code that calls them does not.
Now two stores made from the same class. Predict what they print.
Type exactly what this prints, one value per line.
class Store:
def __init__(self):
self.data = {}
def set(self, key, value):
self.data[key] = value
def get(self, key):
return self.data.get(key, "")
a = Store()
b = Store()
a.set("load", "queued")
b.set("load", "done")
a.set("load", "running")
print(a.get("load"))
print(b.get("load"))
print(b.get("ship") == "")
Part 2: what did a key hold at second t?
The interviewer adds time. set(key, value, timestamp) records the second of each write, and get(key, timestamp) returns the value of the latest write at or before that second, or "" if there is none. The timestamps of set calls only grow.
A dict of latest values cannot answer, because each write erases the one before. The notebook must keep every write. For each key, keep two lists side by side: times[key], the seconds of its writes, and values[key], what was written at each of those seconds. Position i in one matches position i in the other. After four writes to load:
| position | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
times["load"] | 2 | 5 | 6 | 9 |
values["load"] | queued | running | failed | running |
Each new second is larger than every earlier one, so appending keeps times sorted. get("load", 7) asks for the last position whose second is at most 7. That is position 2: the job failed at second 6 and was not restarted until second 9, so the answer is "failed".
A sorted list and a question about a boundary call for binary search: look at the middle position, and keep only the half that can still hold the answer. Ask of each position: is times[i] after 7? Left to right the answers are no, no, no, yes. Because the list is sorted, once a second is after 7, every later one is too.
The first yes is the first write that is too late, so the write we want sits one position before it. Finding the first yes is the first-true template from the binary search lesson:
lostarts at 0 andhiat the length, 4, so the possible answers are the positions 0 to 4. Position 4, one past the end, means no write is too late.- Each pass looks at
mid = (lo + hi) // 2, the middle of that range. - A yes means the first yes is
midor earlier, sohi = mid. A no means it comes aftermid, solo = mid + 1. - The loop stops when
lo == hi, with one possible answer left.
The helper returns lo - 1, which is -1 when no write is early enough.
Before you step through, guess how many times the loop body runs on these four seconds.
def last_at_or_before(times, timestamp):lo, hi = 0, len(times)while lo < hi:mid = (lo + hi) // 2if times[mid] > timestamp:hi = midelse:lo = mid + 1return lo - 1
(nothing printed yet)The test is "after", written >, and the choice matters only at a boundary. A write made exactly at the asked second must count. See what one character changes:
A teammate writes the search with >= instead of >:
def last_at_or_before(times, timestamp):
lo, hi = 0, len(times)
while lo < hi:
mid = (lo + hi) // 2
if times[mid] >= timestamp:
hi = mid
else:
lo = mid + 1
return lo - 1
times["load"] is [2, 5, 6, 9] and values["load"] is ["queued", "running", "failed", "running"]. get returns values["load"][i] for the position i the search returns, or "" when it returns -1. What does get("load", 5) return with this version?
Choose one answer, then check.
How fast is it? A get on a key with k writes costs O(log k), not the O(k) of a scan. The possible answers are the positions from lo to hi, and each pass leaves at most half of them, rounded up. In the trace above, the five possible answers, 0 to 4, went to two after the first pass (3 and 4), then to one.
A key has been written 1,000 times. At most how many times does the while loop in last_at_or_before run for one get? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Now build part 2 as a class, TimeMap, from a blank editor if you can. Put the search in its own function, and keep the class to storing and looking up. Before you submit, trace a second equal to a write's second and a second before the first write.
The class stores; the function searches. In the reference solution, set only appends (after making two empty lists for a new key), and get only asks last_at_or_before for a position and reads the value there. A single list of (second, value) pairs per key works too; then the search reads pairs[mid][0]. And bisect.bisect_right(times, timestamp), from the binary search lesson, returns the first index whose second is after timestamp, so subtracting 1 gives the same index in one call. Name it, and write the loop when the interviewer asks for it.
Part 3: deleting without losing the past
How do you delete a key without losing what it held before? Part 3 adds delete(key, timestamp). From that second on, get returns "" until the key is written again, but earlier seconds still see the old values. After load is deleted at second 12, a question about second 7 must still get "failed".
So removing the key's lists is wrong: it would erase the past. Instead, record the delete as one more write, with a marker for its value. None works as the marker, because in this store every real value is a non-empty string. A marker like this is often called a tombstone: it says "nothing here from this second until the next write".
Deletes follow the same rule as set, each second larger than the last (ask, if the interviewer does not say). So times stays sorted, and the search does not change at all. Only the read needs one more check: if the write it finds is a tombstone, return "".
The trace runs the idea on the lists for load from part 2. It appends the delete at second 12, then asks about seconds 7 and 13. Before you step through, predict both answers.
def last_at_or_before(times, timestamp):lo, hi = 0, len(times)while lo < hi:mid = (lo + hi) // 2if times[mid] > timestamp:hi = midelse:lo = mid + 1return lo - 1times = [2, 5, 6, 9]values = ["queued", "running", "failed", "running"]times.append(12)values.append(None)def get(timestamp):i = last_at_or_before(times, timestamp)if i < 0 or values[i] is None:return ""return values[i]print(get(7))print(get(13) == "")
(nothing printed yet)Now make the same change inside the class. Reuse what part 2 already has: a delete is a set with a special value.
The interviewer's part 3: add delete(key, timestamp). From second timestamp on, get returns "" until the key is written again; seconds before it still see the old values. Deletes follow the same rule as set: each timestamp is larger than every one before it.
The starter holds a working part 2. Change as little as you can, then press Watch it run.
raise NotImplementedError, then press Run tests. Each check says what it expects.What made each part small
Why were parts 2 and 3 so small? Look back at what each one changed. Part 2 replaced the notebook, changed both methods, and added one function. Part 3 added a one-line method and one check in get; the search did not change. Three habits kept the changes that small:
- Only the class's methods touch the notebook. Callers say
setandget, neverstore.data[key]. When part 2 swapped one dict of values for two dicts of lists, callers passed a timestamp and learned nothing else. - Each mechanism lives in its own small function. The search is
last_at_or_before, with one job that fits in one sentence: the last position whose second is at mosttimestamp, or -1. You can trace it alone and test it alone, and part 3 reused it as it was. - A new kind of change goes through an existing door.
deleteis asetwith the valueNone, so the rule that keepstimessorted covers deletes with no new code.
Two more habits are about how you spend the round's minutes. Finish and test each part before you start the next: correctness still dominates at mid level (platform data), so make each part right before you add to it. And do not build part 3 before you are asked: you do not know what it will be, and a guessed feature is untested code you must still read and defend.
Put the first habit to work on a part 1 whose part 2 you have not seen.
Part 1 of a build asks for set(key, value) and get(key). You do not know what part 2 will be. Which way of writing part 1 keeps part 2 smallest?
Choose one answer, then check.
A second build: undo for transactions
How do you undo a group of changes without copying the whole store? The second problem grows a store the same way. Its part 1 is the store from part 1 of this lesson, with two differences: get returns None for a missing key, and delete(key) removes a key. Part 2 adds transactions. A transaction is a group of changes kept or undone as a whole: begin() opens one, rollback() undoes every set and delete made since that begin, and commit() keeps them. Both close the transaction.
Brute force first: copy the whole dict at begin. A rollback swaps the copy back in; a commit throws it away. It is correct, but every begin copies the whole store: O(n) for n keys, even when the transaction changes one key.
A rollback needs only the keys the transaction changed, and what each held before. So the transaction keeps an undo record: a dict from each key it changed to the value that key held right before the transaction first changed it, or None if the key held nothing. A stored value is never None in this store, so a saved None can only mean "held nothing". Two rules make it right:
- Save each key once, before its first change. After
set("batch", 500)and thenset("batch", 800), a rollback must restore the value from before both, so the second change must not overwrite what was saved. - Save before every kind of change. Both
setanddeletecall one helper,_remember(key), before they touchdata. A leading underscore marks a method meant only for the class's own use._rememberis the one door into the record.
The trace runs one transaction on a small settings store. self.undo is None while no transaction is open. Before you step through, predict: after the four changes inside the transaction, how many entries does the undo record hold, and what does it save for mode?
class KVStore:def __init__(self):self.data = {}self.undo = Nonedef _remember(self, key):if self.undo is not None and key not in self.undo:self.undo[key] = self.data.get(key)def set(self, key, value):self._remember(key)self.data[key] = valuedef get(self, key):return self.data.get(key)def delete(self, key):if key in self.data:self._remember(key)del self.data[key]def begin(self):self.undo = {}def rollback(self):if self.undo is None:return Falsefor key, old in self.undo.items():if old is None:self.data.pop(key, None)else:self.data[key] = oldself.undo = Nonereturn Truedef commit(self):if self.undo is None:return Falseself.undo = Nonereturn Truestore = KVStore()store.set("batch", 100)store.set("retries", 3)store.begin()store.set("batch", 500)store.set("batch", 800)store.delete("retries")store.set("mode", "fast")print(store.get("batch"), store.get("retries"))store.rollback()print(store.get("batch"), store.get("retries"), store.get("mode"))
(nothing printed yet)Now keep a record yourself, with plain functions in place of the class.
A transaction is open, with undo as its record. Type exactly what this prints.
data = {"a": 1, "b": 2}
undo = {}
def remember(key):
if key not in undo:
undo[key] = data.get(key)
def set_value(key, value):
remember(key)
data[key] = value
def delete(key):
if key in data:
remember(key)
del data[key]
set_value("a", 5)
delete("b")
set_value("c", 9)
set_value("a", 6)
print(undo["a"], undo["b"], undo["c"])
print(data.get("a"), data.get("b"))
Transactions inside transactions
What changes when transactions nest? In part 3, a begin inside an open transaction opens an inner one, and rollback and commit act on the innermost only. When an inner transaction commits, its changes join the outer one, so a later rollback of the outer transaction undoes them too.
One record becomes a stack of records, one per open transaction, innermost on top. A stack (module 5) is a list you add to and take from at one end only, the top; here the top is the end of the list, undo[-1]. begin pushes an empty record, _remember saves into the top one, and rollback pops the top record and puts its old values back. set, get and delete do not change at all, because they reach the record only through _remember. One door into the record is what keeps part 3 small.
The one new rule is in commit. An inner commit cannot drop its record, because the outer rollback must still undo those changes. So it merges the inner record into the outer one, keeping the outer entry when both have the key. The outer entry is older: it holds the value from before the outer begin, which is what an outer rollback must restore. A key that only the inner transaction changed keeps its inner entry, because the outer transaction had not touched it, so its value at the inner begin was also its value at the outer begin.
Here is the merge on real records. x held 1 when the outer transaction began, and the outer transaction set it to 2. Then the inner transaction began, set x to 3 and created y with 9. So the outer record is {"x": 1} and the inner record is {"x": 2, "y": None}. The trace runs the merge part of commit on that stack, drawn with its top at the top. Before you step through, predict the outer record after the merge.
undo = [{"x": 1}, {"x": 2, "y": None}]inner = undo.pop()outer = undo[-1]for key, old in inner.items():if key not in outer:outer[key] = oldprint(outer)
(nothing printed yet)Now work a longer sequence by hand, with a delete in it, before you write the code.
On paper, keep two columns: data and the stack of undo records, innermost last. Write dicts in shorthand, such as {a: 1}. Run this sequence and write both columns after every line:
set("a", 1)
begin() # outer
set("a", 2)
set("b", 5)
begin() # inner
set("a", 3)
delete("b")
set("c", 7)
commit() # inner
rollback() # outer
Then answer: how many keys does the store hold after the outer rollback?
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Now write all three parts. Part 1 is the store from the trace without transactions, part 2 is the trace, and part 3 is the stack and the merge.
Part 3 touched only the transaction code. __init__ starts an empty stack, begin pushes, _remember saves into the top record, rollback pops, and commit pops and merges. Two details are often missed: compare a saved value with is None, never if old:, because 0 and "" are real values; and with nothing open, commit and rollback return False before touching anything.
Last, practice the moment the interviewer adds part 2.
Your part 1 store (set, get, delete over a dict) works. The interviewer says: "Now add begin, rollback and commit." Write what you would say before you type: the plan, where it hooks into part 1, the cost, and how you will test it.
Saved in this browser as you type.