The four-level online coding test
- How the four-level test runs and scores, and why you can't skip a stuck level
- Read each level as a data model, and store records that survive the next level
- Send every read through one helper and every write through another, so a new rule lands in one place
- Write every time window as start <= now < end, and test the edges where off-by-one bugs hide
- Sort with every tie-break, scan by prefix, find the latest entry at or before a time, and restore snapshots correctly
- Refactor with every test passing, and pace 90 minutes over four levels
In-memory database
Anthropic and Airbnb candidates report the same first coding round: an online test on CodeSignal, one problem in four levels, 90 minutes on the clock (4 reports). When it starts, the screen shows a problem like this one, and only its first level:
Build a simple in-memory database. Its requirements grow level by level, and each level opens only when every test so far passes, so plan your code for change.
Level 1. The database holds records. Each record has a unique key, and holds fields, each with a value. Keys, fields and values are all strings.
set(key, field, value)storesvalueunderfieldin the recordkey. It creates the record if there isn't one, and replaces the value if the field already has one.get(key, field)returns the value, orNoneif the record or the field doesn't exist.delete(key, field)removes the field. It returnsTrueif the field existed, andFalseif it didn't.
Call Returns set("user1", "name", "Ada")set("user1", "city", "London")get("user1", "name")"Ada"get("user1", "email")Nonedelete("user1", "name")Truedelete("user1", "name")False
Level 1 looks easy, and it is. The test is in what comes after it: level 2 adds listing a record's fields in order, level 3 adds values that expire, and level 4 adds backups. Each one builds on the code you already wrote, and every earlier test keeps running.
The system itself changes from candidate to candidate. Candidates report a bank, a recipe manager, a task manager or an in-memory database, picked at random when the test starts (2 sources). The skills carry over from one system to the next, so this lesson practices them on three: your database, a task manager and a bank. The full problem at the end is the database.
Level 1 is the warm-up, and you write it over the next three screens, one method at a time. The steps after it teach what levels 2, 3 and 4 need. At the end you solve the whole problem, level by level, in an interview simulation with a 90-minute clock.
This lesson opens the coding builds, where the coding patterns come together. The database is a dict of dicts from the hash maps lesson, its scans sort the way the sorting steps below teach, and its expiry uses the half-open windows from the intervals lesson.
Store a record as a dict inside a dict
On the test, the statement stays on screen while you code. Level 1 has three methods, and you write them one at a time, starting with set:
set(key, field, value)storesvalueunderfieldin the recordkey. It creates the record if there isn't one, and replaces the value if the field already has one.
Before any code, decide how to store the data. A record is a key that holds fields, and each field holds a value. So the database is a dict from key to a dict from field to value. Here it is by hand:
records = {}
records["user1"] = {"name": "Ada"}
records["user1"]["city"] = "London"
print(records)
{'user1': {'name': 'Ada', 'city': 'London'}}
The second line made the record. The third added a field to a record that was already there. set has to do both, depending on whether the key is new. setdefault does exactly that: it returns the dict stored under a key, and stores an empty one there first if the key is missing.
inner = records.setdefault("user2", {})
inner["name"] = "Alan"
print(records["user2"], records.setdefault("user1", {}))
{'name': 'Alan'} {'name': 'Ada', 'city': 'London'}
For the new key it made an empty record. For user1 it handed back the record that was already there, untouched.
In the editor, write set. It prints the records after three calls.
A missing record or field answers None
Next, get:
get(key, field)returns the value, orNoneif the record or the field doesn't exist.
There are two ways to be missing: no record at all, or a record without that field. dict.get handles both without an error: it returns None for a missing key, or a default that you pass it. Here it is on a phone book, a dict of dicts like yours:
phones = {"ana": {"home": "555-0101"}}
print(phones.get("ana", {}).get("home"))
print(phones.get("ana", {}).get("work"))
print(phones.get("ben", {}).get("home"))
555-0101
None
None
For a missing person, phones.get("ben", {}) gives an empty dict, so the second .get still has a dict to work on. Square brackets, phones["ben"], would raise a KeyError instead.
In the editor, set is written, and you write get. It prints Ada, then None twice.
delete says whether it removed something
Last, delete:
delete(key, field)removes the field. It returnsTrueif the field existed, andFalseif it didn't.
in asks whether a dict has a key, and del removes one. On the phone book:
ana = phones.get("ana", {})
print("home" in ana, "work" in ana)
del ana["home"]
print(phones)
True False
{'ana': {}}
del on a key that isn't there raises a KeyError, so check with in first. Check the field, not its value: a field can hold the empty string, and it still exists.
In the editor, set and get are written, and you write delete. It prints True, then False, then what's left of the records.
Level 2 changes the code you already wrote
You just passed level 1. On the test, this is when level 2 opens: a new statement appears, and every level 1 test keeps running until the 90 minutes are up.
| Working on | Level 1 tests | Level 2 tests | Level 3 tests | Level 4 tests |
|---|---|---|---|---|
| level 1 | run | locked | locked | locked |
| level 2 | run | run | locked | locked |
| level 3 | run | run | run | locked |
| level 4 | run | run | run | run |
Candidates describe exactly this. Each new stage unlocked only once every test of the current one passed, and that forced a refactor (1 report). Backward compatibility seemed to need keeping as the levels went on (2 sources). CodeSignal's own outline puts it in one sentence: "candidates must reuse, encapsulate, and refactor earlier code to maintain backward compatibility." Backward compatibility means every old call still returns what it returned before. OpenAI and Netflix candidates report similar builds in live rounds, key-value stores and caches that expire entries (4 sources).
Here is a small version of that moment. Say level 2 adds one thing to get:
get(key, field, default=None)returnsdefaultwhen the record or the field doesn't exist.
A working level 1 database is in the editor, the same three methods you just wrote. Change the get method so that it also accepts a default, and make sure every level 1 call still gives the same answer as before.
You can't see the next level, and you can't skip this one
You just changed level 1's get for level 2, and every old call still had to work. The whole test runs like that.
Each level opens only when the one before passes every test. What does a level you can't finish do to your score?
Turn each level into a data model
Spend the first two minutes of every level reading, not typing. Then write what you read as a comment at the top of the class.
This part shows each idea on the task manager first, one of the other systems the test hands out. It's small, which makes the ideas easy to see: each task has a name, a command and sometimes a deadline, and the code calls it the scheduler. Each idea then lands in your database, and in the full problem at the end. Here's the scheduler's data model, at the level where deadlines arrive:
# name -> Task(command, deadline)
# a deadline of None never expires
# schedule(name, command, deadline=None)
# replaces any task with that name, deadline and all
# status(name, now) -> command, or None
# None once now >= deadline
# cancel(name, now) -> True if a live task was removed
# pending(now) -> live names, sorted
That comment is a data model: what you store, under which key, and what each call gives back. It describes one dict:
self._tasks: name | Task |
|---|---|
| backup | command tar, deadline 100 |
| report | command make, deadline None |
Five questions fill in the model
- What is the key, and what does each record hold besides its value?
- What comes back when something is missing:
None,False, an empty list, an error? - What order do lists come back in, and how are ties broken?
- What happens on a repeat write: replace, reject or merge?
- Which comparisons sit on a boundary, and is each one inclusive or exclusive?
Store a record, not a bare value
| Level | What backup holds | When deadlines arrive |
|---|---|---|
| 1, a bare value | tar | a deadline has nowhere to go |
| 3, a record | Task(tar, 100) | a new field is one more line |
Say the scheduler's level 1 has no deadlines. Then self._tasks[name] = command passes every test. When deadlines arrive, every line that touches self._tasks has to change at once, with the timer running.
A record is one small object that holds everything about one entry. A record type costs a few lines up front:
from dataclasses import dataclass
@dataclass(frozen=True)
class Task:
command: str
# None: no deadline
deadline: int | None = None
print(Task("tar"))
print(Task("tar", 100))
Task is a frozen dataclass whose deadline defaults to None. What does print(Task("tar")) show?
A question about the past needs a history
Take the bank, the third system in this lesson and its worked example at the end: deposits and withdrawals arrive with a time, and a later level asks for an account's balance at any time t. When a level asks about the past like that, one current value can't answer. Keep a history instead: a list of (time, value) pairs per key, added to as calls arrive.
# acct -> [(t, balance after the change at t), ...], oldest first
self._history = {}
Here is one account after a deposit of 80 at time 2 and a withdrawal of 30 at time 5:
When times only increase, appending keeps every list sorted. That's what makes a question about time t cheap to answer. The worked example below makes this switch at level 3.
In the editor, write the ledger's deposit so that each change adds a (time, balance) pair to the account's history.
Make room for the next level, but don't build it
You can't see the next level. But specs like these tend to grow in five directions:
| Direction | What it adds |
|---|---|
| time | expiry, the state as of t |
| order | sorted lists, the top n |
| totals | counts, sums |
| history | versions, snapshots |
| across records | transfers, merges |
You can't see level 3. What is worth building for it at level 1?
Mid-refactor at level 3, a step turns a level 1 test red, and the fix isn't obvious within a minute. What do you do?
One path for reads, one for writes
Copied rules drift apart
Here are three scheduler methods. Each one carries its own copy of the rule for a live task.
class DriftedScheduler:
def __init__(self) -> None:
self._tasks: dict[str, Task] = {}
def schedule(self, name: str, command: str, deadline: int | None = None) -> None:
self._tasks[name] = Task(command, deadline)
def status(self, name: str, now: int) -> str | None:
task = self._tasks.get(name)
if task and (task.deadline is None or now < task.deadline):
return task.command
return None
def cancel(self, name: str, now: int) -> bool:
task = self._tasks.get(name)
# drifted to <=
if task and (task.deadline is None or now <= task.deadline):
del self._tasks[name]
return True
return False
def pending(self, now: int) -> list[str]:
# no rule at all
return sorted(self._tasks)
drifted = DriftedScheduler()
drifted.schedule("backup", "tar", deadline=100)
print(drifted.status("backup", 100))
print(drifted.pending(100))
print(drifted.cancel("backup", 100))
Each method carries its own copy of the live-task rule. backup is due at 100, and the clock reads 100. What do status, pending and cancel say?
Put the rule in one helper
Write the rule once, in a private helper, and send every method through it:
class Scheduler:
def __init__(self) -> None:
self._tasks: dict[str, Task] = {}
def schedule(self, name: str, command: str, deadline: int | None = None) -> None:
self._tasks[name] = Task(command, deadline)
def _live(self, name: str, now: int) -> Task | None:
"""The task if it's live at now, else None."""
task = self._tasks.get(name)
if task is None or (task.deadline is not None and now >= task.deadline):
return None
return task
def status(self, name: str, now: int) -> str | None:
task = self._live(name, now)
return task.command if task else None
def cancel(self, name: str, now: int) -> bool:
if self._live(name, now) is None:
return False
del self._tasks[name]
return True
def pending(self, now: int) -> list[str]:
return sorted(name for name in self._tasks if self._live(name, now))
scheduler = Scheduler()
scheduler.schedule("backup", "tar", deadline=100)
print(scheduler.status("backup", 100))
print(scheduler.pending(100))
print(scheduler.cancel("backup", 100))
Now every method reads through one _live helper. Same task, same moment. What do the three say?
A new level wants _live to act differently for one caller. What do you do?
backup is due at 100. Then it's scheduled again with no deadline, and the code changes the old record's command in place. Is it live at 150?
Time windows are half-open
Level 3 adds time: every call carries a timestamp, and a record can expire.
A record written at 10 with a TTL of 5 is gone at 15
A record with a TTL lasts that long after its write. Every timed level asks the same question at its edges: is the record still there at 15?
Write every window as half-open, start <= now < end. The start is in. The end is out. When the spec spells out its own inequality, follow that one.
Half-open windows add up and line up
Half-open keeps the arithmetic honest:
- The length is
end - start. A TTL of 5 written at 10 covers 10, 11, 12, 13 and 14: five times. - Windows tile.
[0, 10)and[10, 20)share the boundary 10, and every time falls in exactly one of them. - Python already works this way.
range(10, 15)ands[10:15]both stop before 15.
Dijkstra made the case in 1982. With this convention, the difference between the two bounds is the length, and two ranges side by side share a bound. He also reported how the other conventions went in Mesa, a language from Xerox PARC that offered all four: they were "a constant source of clumsiness and mistakes."
In the editor, write that one time check: is a record written at written with a TTL of ttl alive at now?
Time moves only when a call passes it in
In this test, nothing happens between calls.
x is stored at 10 with a TTL of 5, and no call runs from 11 to 19. Is x still in the dict at 17?
Two requests per 10 seconds, arriving at 0, 5, 9, 10, 11 and 15. With half-open windows, the request at 0 stops counting at 10. Which requests pass?
Sort explicitly, every time
The scans return their fields in a stated order, and ties are where answers go wrong.
Give sorted a tuple with every tie-break in it
balances = {"zoe": 40, "ana": 75, "ben": 10}
print(sorted(balances.items()))
print(sorted(balances.items(), key=lambda row: (-row[1], row[0])))
key=lambda row: (-row[1], row[0]) on zoe 40, ana 75 and ben 10. What order comes out?
Strings sort by code point
Sorting strings has one more surprise.
print(sorted(["ana", "Zoe", "item10", "item9"]))
What does sorted(["ana", "Zoe", "item10", "item9"]) give?
A prefix scan is a filter
Level 2's scan returns the fields that start with a prefix.
| Prefix | apple | apricot | fig | pear | plum |
|---|---|---|---|---|---|
ap | yes | yes | |||
| empty | yes | yes | yes | yes | yes |
A prefix scan lists the keys that start with a given string: [k for k in sorted(d) if k.startswith(prefix)]. Every string starts with the empty string. So the full listing is the same code with prefix="", and one method serves both.
Sorting on every call costs O(n log n), which is fine at test sizes. After the sort, the matches sit next to each other. A faster version uses that, under What interviewers ask next.
A statement is built straight from list(self._balances.items()). The accounts were opened zoe, ana, ben. What order comes out?
The latest entry at or before a time
A read at a past moment has to find the right version in a history of writes. Level 4's restore asks the same question of its backups.
Walk back from the newest entry
Say rates were published at times 0, 10 and 20, and kept oldest first: [(0, 1.10), (10, 1.12), (20, 1.08)]. To read the rate at time t, walk the list from the newest entry back, and return the first rate published at or before t. If every entry is later than t, no rate existed yet, so return None.
Rates were published at 0, 10 and 20. The loop walks backward and returns the first one at or before t. What does it give at 15, 25 and -5?
bisect_right minus one does it in O(log n)
When you want O(log n), or an interviewer asks about scale, the bisect module does the search. Python's docs even ship this recipe, as a function called find_le.
from bisect import bisect_left, bisect_right
print(bisect_left([2, 5, 5, 7], 5), bisect_right([2, 5, 5, 7], 5))
What do bisect_left([2, 5, 5, 7], 5) and bisect_right([2, 5, 5, 7], 5) give?
At t = -5, bisect_right(times, -5) is 0, so i is -1. Why does the code check i >= 0?
Snapshots and restore
Some levels save the state and bring it back later. The saved copy is a snapshot. It asks three things of you: what to copy, what to keep, and what time means after the restore.
Saving a name saves nothing
import copy
tasks = {"backup": {"deadline": 130}}
# a second name for the same dict
saved = tasks
# a new outer dict holding the same inner dicts
shallow = dict(tasks)
# new all the way down
deep = copy.deepcopy(tasks)
tasks["backup"]["deadline"] = 999
tasks["report"] = {"deadline": 200}
print("saved ", saved)
print("shallow", shallow)
print("deep ", deep)
After the inner deadline becomes 999 and report is added, which copy sees which change?
A snapshot is a read, so it skips the dead
A snapshot goes through the same check as every other read. Expired records are still in your dict, because nothing deleted them.
Time left or end time: the spec picks
A record saved with an end time has to come back with one. There are two honest designs, and the spec picks:
- Time keeps flowing. Store absolute end times and restore them unchanged. Redis works this way: it stores each key's expiry as an absolute Unix timestamp, so time flows on even while the server isn't running.
- The clock stops while saved. Store the time left,
end - saved_at, and restore it asrestored_at + left.
Take a timer that ends at 130, saved at 110 and restored at 500:
| What the snapshot stored | End after the restore | At 500 |
|---|---|---|
| the time left, 130 - 110 = 20 | 500 + 20 = 520 | 20 to go |
| the end time, 130, used as is | 130 | already over |
| the end time, 130, added to the restore time | 500 + 130 = 630 | 130 to go |
Read the spec for words like remaining, left, as of or recalculated. They tell you which design it wants. Then the snapshot should store what the restore needs.
Restore the latest snapshot at or before the time asked for
When there are several snapshots, the restore wants the latest one at or before the time it names. That's the latest-entry query above, with its trap: a forward loop that returns the first match restores the oldest snapshot.
Now your database's level 4. In the editor, fill in the loop in backup.
A worked example: a ledger in four levels
Here's a small system of our own, built the way this lesson says, with outputs from a real run. The spec:
- Level 1.
deposit(t, acct, amount)returns the new balance.withdraw(t, acct, amount)returns the new balance, orNoneif the account holds less thanamount, and then nothing changes. Amounts are positive, and times increase from call to call. - Level 2.
top(t, n)returns thenlargest balances as(acct, balance)pairs, ties broken by account name. - Level 3.
balance_at(acct, t)returns the balance after every operation at or beforet, orNoneif the account had no balance yet. - Level 4.
rollback(t)undoes every operation aftert.
Levels 1 and 2: one balance per account
class Ledger:
def __init__(self) -> None:
# acct -> balance
self._balances: dict[str, int] = {}
def deposit(self, t: int, acct: str, amount: int) -> int:
self._balances[acct] = self._balances.get(acct, 0) + amount
return self._balances[acct]
def withdraw(self, t: int, acct: str, amount: int) -> int | None:
if self._balances.get(acct, 0) < amount:
return None
self._balances[acct] -= amount
return self._balances[acct]
def top(self, t: int, n: int) -> list[tuple[str, int]]:
return sorted(self._balances.items(), key=lambda row: (-row[1], row[0]))[:n]
Before you read on: ana holds 80 and calls withdraw(4, "ana", 100). What comes back?
ana, ben and cy each hold 50 at time 6. What does top(6, 3) return?
The run
Run the finished ledger on a sequence of calls, and check each return.
rollback(5) undoes every operation after time 5. Which one goes?
Pacing 90 minutes over four levels
Ninety minutes for four levels goes fast, so plan the clock before you start.
CodeSignal's brief gives each level a range of minutes. To finish all four in 90, which end of each range do you have to hit?
Inside a level, run one loop and give a stuck test five minutes
Run the same loop inside every level:
- Read for two minutes and write the model comment.
- Make the smallest method pass, and run the tests.
- Fill in the rest, then add your own boundary tests.
When a test won't pass, change how you look at it:
- Give it five minutes of tries.
- If they found a new fact, keep going.
- If not, reread the spec sentence the test covers, and run its input by hand.
- Then check, in order: the boundary, the missing case, the sort order, the types.
Five minutes on one failing test, and no try found a new fact. What next?
What interviewers ask next
Two readers grade your code
The first reader is the test suite. CodeSignal's datasheet says results are scored automatically. So in the auto-scored assessment the tests decide your score, and design shows up as time. By the last level, the brief says, the more reusable your earlier methods are, the easier the refactor. A tangle at level 2 gets paid for at level 4.
The second reader is a person, in a live round or anywhere your code gets read. OpenAI says that in engineering interviews it looks for a well-designed solution, high-quality code, optimal performance and good test coverage (1 source). The practice problem is graded on those four. In a build that grows, that looks like this:
- Names that say what they hold:
deadline,saved_at,left. Nevert2ortmp. - One helper per rule (
_live,_balance,_post), so a reader checks each rule once. - No copied filters, no dead code, no debugging prints left behind.
- Public methods that read like the spec: find the record, check it, act.
- Costs you can state, and the next step at scale.
- A few tests of your own, aimed at the edges: the start,
end - 1,end, the missing key, the overwrite, the restore.
The follow-ups
Walk me through your code.
What does each call cost? In the scheduler, status is O(1). pending is O(n log n), for the sort. A scan sorts on every call, which is fine at test sizes.
At scale, a heap of deadlines and a sorted list of keys do most of the work
After the costs comes How would this scale?
Expired records pile up in the dict and get filtered out on every read. What expires them as they end?
Where this shows up
The reports behind this lesson, each with its source.
CodeSignal online assessment (candidate, March 2024, role not stated): 4 levels to finish in 90 minutes.
Senior candidate note (late April 2026) on Hello Interview's in-memory database question: the CodeSignal problem was divided into 4 levels.
AI/ML Engineer candidate (San Francisco, dated 2025-01-21): in the online screener, later questions unlocked only after the earlier ones were done.
Research Fellowship applicant (named blog, Feb 2025): in the online coding challenge each new stage unlocked only after all tests passed, which forced a refactor.
Same late-April 2026 Senior note: backward compatibility had to be preserved as the levels progressed.
DS candidate (L4, US, interview about mid-2026, rejected): the first screen was a 4-level CodeSignal.
A coach's newsletter (Sundeep Teki, 2026-06-07) says Anthropic's CodeSignal screen 'appears to have grown' from four stages to six, based on three of his clients reporting it in the prior month; Anthropic has not announced it. Reports of 4 levels come from April 2026 (ant-073) and about July 2026 (ant-078), the latter after this newsletter.
Software Engineer online assessment (Sep 2026): the standard CodeSignal Industry Coding Assessment.
Another Software Engineer OA (Aug 2026): 90 minutes, four levels.
Hello Interview's candidate timeline lists the SQL-like in-memory database question for OpenAI mid-level candidates in late March 2026 and early June 2026.
A second prep site lists an in-memory key-value database (set/get/delete, compare-and-set, TTL, atomic multi-key) for an OpenAI SWE technical screen, posted 2025-07-31.
Senior+ Software Engineer in Ads, IC5 (interviewed Oct 2026, rejected): the phone screen was a key-value store with TTL.
Hello Interview's Netflix timeline has the same question from a Senior candidate in early October 2026.
Engineering interviews are graded on solution design, code quality, performance and test coverage.
“For engineering interviews, we generally look for well-designed solutions to the challenge, high-quality code, optimal performance, and good test coverage.”
Practice
Sources (12)
- What are the Industry Coding Assessment (ICA) rules? · CodeSignal Support · Sep 14, 2026
“Given the progressive nature of the requirements, candidates must reuse, encapsulate, and refactor earlier code to maintain backward compatibility.”
- Industry Coding Skills Evaluation Framework: Technical Brief · CodeSignal (PDF) · Sep 11, 2024
“Typically, candidates should expect to spend 10-15 minutes on this level while writing 15-20 lines of code.”
- Industry Coding Framework datasheet · CodeSignal (PDF) · Nov 9, 2022
“Results are automatically scored, so internal engineers no longer need to manually review responses.”
- Why numbering should start at zero (EWD 831) · E.W. Dijkstra Archive, University of Texas at Austin · Aug 11, 1982
“Extensive experience with Mesa has shown that the use of the other three conventions has been a constant source of clumsiness and mistakes, and on account of that experience Mesa programmers are now strongly advised not to use the latter three available features.”
- Built-in Types · Python 3 documentation · Nov 5, 2026
“Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.”
- Sorting Techniques · Python 3 documentation · Nov 5, 2026
“Sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.”
- bisect: Array bisection algorithm · Python 3 documentation · Nov 5, 2026
“Find rightmost value less than or equal to x”
- copy: Shallow and deep copy operations · Python 3 documentation · Nov 5, 2026
“Assignment statements in Python do not copy objects, they create bindings between a target and an object.”
- SET · Redis documentation · Sep 18, 2026
“Any previous time to live associated with the key is discarded on successful SET operation.”
- EXPIRE · Redis documentation · Sep 18, 2026
“Keys expiring information is stored as absolute Unix timestamps (in milliseconds in case of Redis version 2.6 or greater). This means that the time is flowing even when the Redis instance is not active.”
- An example of preparatory refactoring · martinfowler.com · Jan 5, 2015
“When you're wearing the refactoring hat, every change you make preserves observable behavior, keeps the tests green, and allows you to make many small changes without going near a debugger.”
- The Wrong Abstraction · sandimetz.com · Jan 20, 2016
“If you find yourself passing parameters and adding conditional paths through shared code, the abstraction is incorrect.”