iq.lab
Python starts when a code cell comes near or you run one
14 Interview mode

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.

About 1 hour 35 minutes, with the 2 problems worked in it
By the end you can
  • 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.

Step throughPart 1, a store of job statuses
Step 1 of 25
Line 1 is about to run.
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, "")
store = Store()
store.set("load", "queued")
store.set("ship", "queued")
store.set("load", "running")
print(store.get("load"))
print(store.get("join") == "")
Names
no names yet
Output
(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.

PredictTwo stores, one class

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:

position0123
times["load"]2569
values["load"]queuedrunningfailedrunning

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:

  • lo starts at 0 and hi at 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 mid or earlier, so hi = mid. A no means it comes after mid, so lo = 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.

Step throughThe last write at or before second 7
Step 1 of 14
Line 1 is about to run.
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
Names
no names yet
Output
(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:

Quick checkOne character at the boundary

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.

Work it outHow many passes?

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.

passes

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.

mediumDesign as codingBinary searchHash maps and sets target 25 min

Time-based key-value store

A settings service never forgets. Every write is stamped with the second it happened, and a read can ask what a key held at any second.

Build a class TimeMap:

  • TimeMap() starts with no keys.
  • set(key, value, timestamp) records that key took the value value at second timestamp.
  • get(key, timestamp) returns what key held at second timestamp: the value of the latest set on that key whose timestamp is at most timestamp. If there is no such set (the key was never written, or only later), return the empty string "".

The timestamps of set calls strictly increase from one call to the next, across all keys. A get can ask about any second, earlier or later than the last write, and changes nothing.

Example 1
Inputset("color", "red", 1), set("color", "blue", 4), get("color", 3), get("color", 4), get("color", 9), get("color", 0)Outputthe four get calls return "red", "blue", "blue", ""

At second 3 the latest write is red, from second 1. At second 4 the blue write counts, because its timestamp is at most 4. At second 0 nothing had been written yet.

Example 2
Inputset("mode", "on", 2), set("size", "big", 3), set("mode", "off", 7), get("mode", 6), get("size", 6), get("mode", 7), get("theme", 7)Outputthe four get calls return "on", "big", "off", ""

Each key has its own history, so the write to size at second 3 does not touch mode. The key theme was never written.

Constraints
  • 0 ≤ timestamp ≤ 107

  • Timestamps of set calls strictly increase across all calls.

  • Keys and values are non-empty strings of lowercase letters and digits.

  • Up to 2 × 105 calls in total. One key can be written up to 105 times.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

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.

Step throughA delete is one more write
Step 1 of 45
Line 1 is about to run.
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 = [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) == "")
Names
no names yet
Output
(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.

Code itPart 3: delete

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.

⌘+Enter runsPython starts when a code cell comes near or you run one
Write your code where the starter says 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:

  1. Only the class's methods touch the notebook. Callers say set and get, never store.data[key]. When part 2 swapped one dict of values for two dicts of lists, callers passed a timestamp and learned nothing else.
  2. 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 most timestamp, or -1. You can trace it alone and test it alone, and part 3 reused it as it was.
  3. A new kind of change goes through an existing door. delete is a set with the value None, so the rule that keeps times sorted 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.

Quick checkA part 1 that survives

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 then set("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 set and delete call one helper, _remember(key), before they touch data. A leading underscore marks a method meant only for the class's own use. _remember is 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?

Step throughOne transaction with an undo record
Step 1 of 86
Line 1 is about to run.
class KVStore:
def __init__(self):
self.data = {}
self.undo = None
def _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] = value
def 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 False
for key, old in self.undo.items():
if old is None:
self.data.pop(key, None)
else:
self.data[key] = old
self.undo = None
return True
def commit(self):
if self.undo is None:
return False
self.undo = None
return True
store = 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"))
Names
no names yet
Output
(nothing printed yet)

Now keep a record yourself, with plain functions in place of the class.

PredictWhat the undo record keeps

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.

Step throughAn inner commit merges into the outer record
Step 1 of 11
Line 1 is about to run.
The outer record at the bottom, the inner record on top.
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] = old
print(outer)
Names
no names yet
Output
(nothing printed yet)

Now work a longer sequence by hand, with a delete in it, before you write the code.

On paperNested transactions by hand

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.

Keys in the store after the outer rollback

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.

mediumDesign as codingHash maps and setsStack target 25 min

Key-value store with transactions

Not solved yetOpen full page

An interviewer hands you this store in three parts. Each part keeps every rule from the parts before it.

Part 1. Build a class KVStore:

  • KVStore() starts empty.
  • set(key, value) stores value under key, replacing any value already there.
  • get(key) returns the value stored under key, or None if there is none.
  • delete(key) removes key and its value. Deleting a key that holds nothing does nothing.

Part 2. Add transactions. A transaction is a group of changes that is kept or undone as a whole.

  • begin() opens a transaction.
  • rollback() undoes every set and delete made since that begin, then closes the transaction.
  • commit() closes the transaction and keeps its changes.
  • rollback() and commit() return True. When no transaction is open, they change nothing and return False.
  • get always returns the newest value, including changes made inside an open transaction.

Part 3. Transactions nest. A begin() while a transaction is open opens an inner one, and rollback() and commit() act on the innermost open transaction only. When an inner transaction commits, its changes join the transaction around it, so a later rollback() of the outer transaction undoes them too.

set, get, delete and begin must take O(1) time on average. rollback() and commit() may take time in proportion to the number of keys the closing transaction changed, but not to the size of the whole store.

Example 1
Inputset("a", 1), set("b", 2), get("a"), delete("a"), get("a"), get("b")Outputget("a") returns 1, then get("a") returns None, get("b") returns 2

Part 1 only: after the delete, a holds nothing.

Example 2
Inputset("x", 10), begin(), set("x", 20), set("y", 5), get("x"), rollback(), get("x"), get("y"), rollback()Outputget("x") returns 20, rollback() returns True, get("x") returns 10, get("y") returns None, rollback() returns False

Inside the transaction, get sees 20. The rollback puts x back to 10 and removes y, which did not exist before. The second rollback finds no open transaction.

Example 3
Inputset("x", 1), begin(), set("x", 2), begin(), set("x", 3), commit(), get("x"), rollback(), get("x")Outputcommit() returns True, get("x") returns 3, rollback() returns True, get("x") returns 1

The inner commit hands x = 3 to the outer transaction, so rolling the outer one back restores 1, the value from before the first begin.

Constraints
  • Keys and values are strings or integers. A value is never None.

  • Up to 106 calls in total.

  • The store can hold hundreds of thousands of keys while each transaction changes only a few.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

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.

Say itThe 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.

A few sentences first: 0 of 60 characters.

Saved in this browser as you type.

Next: How hard problems are built