AlgoViz

The 5-step execution flow

easy 45 min

A fixed order for the 45 minutes of a low-level design round: ask, name, sketch, build, prove.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:38

The 5-step execution flow

1:04Reel

Theory

Read or listen first. About 2 min.

What it is

The flow has five steps. Ask: agree on requirements. Name: find the things and their owners. Sketch: give each class state and methods, choose patterns, data structures and locks. Build: write the core code. Prove: trace it, then extend it.

Each step produces something that the next one uses. Requirements give the nouns. Nouns give the classes. Classes give the code. Code gives something to trace.

The minutes here are for a round of 45: 5, 5, 8, 13 and 14. They are a plan, not a rule of nature. For another length keep the shares: about 10, 10, 20, 30 and 30 percent.

Why it exists

Without a plan, people spend the time where they feel safe: long questions, beautiful boxes. The code starts at minute 35 and nothing is proved.

A fixed order also frees your head. You do not think about what comes next, you think about the problem. And the interviewer can follow, because you say where you are.

The order is cheap to leave and cheap to return to. A question about locks at minute 8 gets a short answer, and then you are back at your step.

A short history

  1. 1945

    George Polya publishes How to Solve It with four phases: understand the problem, devise a plan, carry it out, look back.

  2. 1989

    Kent Beck and Ward Cunningham present CRC cards: walk through a scenario and let each card say what it does. The Name step still works like this.

  3. 1991

    James Martin publishes Rapid Application Development, after work on the approach at IBM. Fixed time boxes later count among its best practices.

Words to know

Time box
A fixed length for a step. At its end you move on with what you have.
Exit line
The sentence that closes a step and asks for agreement.
Functional requirement
What the program does: a student starts a machine.
Non-functional requirement
How well it does it: never two washes in one machine.
Core path
The one action in which most rules meet. Code this first.
Seam
A place where a later change can enter without a rewrite.
Injected clock
Time is passed in as a function, so a test can move it.
Parking list
Good ideas that are out of scope, written down and left.

How it works

Step through the idea, or press Play.

Step 1 of 5

Ask. 0 to 5: requirements

Understand it

Start here

One dish, five cooks, one clock

Five cooks finish one dish. Each does one thing and hands it on. You are all five of them.

The relay in the kitchen
45 min1 Ask2 Name3 Sketch4 Build5 Prove1 dishsoon

The plate never goes back. A cook who finds a mistake says so and fixes it at their own place.

The clock

Five steps, five results

StepMinutesYou doYou leave withExit line
1 Ask0 to 5Questions, then a list5 to 7 requirements, a list of what is outDoes this match what you want?
2 Name5 to 10Nouns, owners, rejected nouns3 to 5 classes, one sentence eachThese keep the rules. I continue with state and methods.
3 Sketch10 to 18Fields, methods, patterns, structures, locksA class diagram with signaturesI would code start and empty now.
4 Build18 to 31The core path, refusals firstTwo methods that are completeLet me trace this.
5 Prove31 to 45Trace 5 minutes, extend 9 minutesA checked core and one extensionThis class is new, these stay.

What each step hands on

Only the extension goes back to the sketch, and it changes one place there.

Behind the clock? Cut scope

We run the whole flow on one prompt: Design the laundry room of a student house. Students see which machines are free, start a program and empty the machine.

Step 1, minutes 0 to 5

Ask

Say the main path first: a student looks, starts a wash, comes back and empties the machine. Then ask about scale, actors and constraints.

Three kinds of scope question

  • Scale

    One room in memory, or many houses on a network? One room changes the answer to a class design.

  • Actors

    Who acts? Students, the caretaker, and time itself: a wash ends although nobody presses a button.

  • Constraints

    Several screens at once? Can a machine or the network fail? Must data survive a restart?

F and N: what it does, and how well

F, functionalN, non-functional
List free machinesAtomic: never two washes in one machine
Start quick (30 min) or cotton (60 min)Size: one room, about 10 machines, in memory
At most two machines per studentExtensible: the house will add rules for starting
Owner empties a finished machineTestable: time can be moved in a test
Others may empty it 15 minutes after the endSeveral screens at once
Out: payment, reservations, faults
In a parking lot the same method gives: assign a spot, pay by card or cash (F), no double booking, 10,000 spots, new payment methods (N).

Minute 1 to 4

  1. You

    A student looks, starts a program, and empties the machine later. Is that the main path?

  2. Interviewer

    Yes.

  3. You

    What if the owner does not come back? Then one person blocks a machine.

  4. Interviewer

    Others may take the clothes out after 15 minutes.

  5. You

    Good, that is a rule about time. May one student use all machines?

  6. Interviewer

    Two at most.

  7. You

    I assume one process, several screens, nothing stored on disk, no payment. Does this match what you want?

Step 2, minutes 5 to 10

Name

Underline the nouns and ask three questions: what holds (container), what is held (item), who takes the request (manager). The full lens is on what an LLD interview tests.

Container, item, manager

ProblemContainerItemManager
Laundry roomRoomMachine, washLaundryRoom
Parking lotFloor, spotVehicle, ticketParkingSystem
ChessBoard, squarePieceGameController
LibraryShelf, sectionBook copyLending desk
In the laundry room container and manager are one class. Two would pass calls on and decide nothing. In a library the member is an actor.

Nouns, judged

NounVerdictBecause
MachineClassHas identity and a rule: one wash at a time
WashSmall recordOwner and end belong together, and never change
RoomClassThe limit per student spans machines
ProgramEnumOnly a number of minutes differs
StudentJust an idWe store no fact about them
TimerNot a classThe state can be computed from the clock
ScreenOutIt calls us

Reject nouns aloud. It is a decision, and it earns as much as a class. How to find owners: entities.

Step 3, minutes 10 to 18

Sketch

Now each class gets state, methods and a rule to keep. Here you also choose patterns, data structures and locks, each with a reason.

The sketch at minute 18

Machine- wash: Wash?+ state(now): State+ start(who, minutes, now)+ empty(who, now, grace)Wash+ owner: Id+ endsAt: int

1/5Machine first

The rule one wash at a time lives in Machine. It may hold a Wash or nothing.

owns (dies together)usesdepends on

Words that point to a pattern

You hearThink ofUse it only if
Several ways to do X, policy, algorithmStrategyBehaviour differs, not just a value
Status changes, idle and activeStateBehaviour differs per state. Else an enum
Notify, subscribe, update othersObserverThe sender must not know the receivers
Undo, redo, history, queue of actionsCommandAn action must be kept or reversed
Create by typeFactoryThe choice is made in more than one place
Only one, shared by allCreate one and pass it inSingleton needs a much stronger reason
One keyword is a hint, not a verdict. All of them: the master matrix.

Data structure and lock, with a reason

NeedChooseLaundry room
Find by key oftenHash mapYes: machine by id
Always the smallest or most urgentPriority queueNo: a list of 10 is scanned
Many yes or no flags, very many itemsBit setNo
Several writers, check then changeOne lock around bothYes: limit and start
At most n at a time may enterSemaphoreNo: we refuse, nobody waits
Many readers, few writers, slow readsRead and write lockNo: reads take microseconds
More: data structures for LLD and concurrency in LLD.

How does a machine become DONE?

BreaksA thread per machine that sleeps
How
start starts a thread, and after 30 minutes it writes DONE.
Limit
Threads to manage, races with empty, and a test that takes 30 minutes.
Choose when
Never here.
WorksA tick that updates all machines
How
Once per second somebody calls tick(now).
Limit
The state is wrong between ticks, and somebody must call it.
Choose when
If something must happen at that moment, such as a message.
StrongCompute it when asked
How
state(now) compares now with the end of the wash.
Limit
Nobody is told when it ends. A message needs a scheduler beside it.
Choose when
Whenever the state follows from time and stored facts.

Deriving fields and methods from requirements step by step: class design.

Step 4, minutes 18 to 31

Build

Write from the inside out: enums and records, then the class with the tightest rule, then the manager. Inside a method: refusals first, then the change. Say why while you type.

The laundry room in the order you would write it

Small types give the rest a vocabulary. Do not stay here.

from dataclasses import dataclassfrom enum import Enumfrom threading import Lockfrom typing import Callable, Protocolclass Refused(Exception):    """A rule said no."""class Program(Enum):    QUICK = 30          # minutes    COTTON = 60class State(Enum):    FREE = "free"    RUNNING = "running"    DONE = "done"@dataclass(frozen=True)class Wash:    owner: str    ends_at: int        # minutes since midnight of day 0

Lines 7 to 8

One exception for every rule that says no. The screen shows its text, and a real bug still looks different.

1 of 4

A start, from tap to answer

States of a machine

Step 5a, minutes 31 to 36

Prove

Choose one good case, one refusal, one race. Use numbers. Write the values beside the code. If you find a bug, say it and fix it.

Trace: two machines, limit 2, grace 15

TimeCallm1 beforeResultm1 after
600start(asha, m1, quick)freeends at 630running
600start(lee, m1, quick)runningrefused: m1 is runningrunning
630empty(lee, m1)donerefused: wait for the ownerdone
645empty(lee, m1)doneok, 645 is not before 645free

The trace as a test, then the extension

The same table as code. If the format allows running, run it.

now = 600                                   # 10:00, and we can move itroom = LaundryRoom([Machine("m1"), Machine("m2")], clock=lambda: now)def refused(action):    try:        action()    except Refused as e:        return str(e)    raise AssertionError("should have been refused")room.start("asha", "m1", Program.QUICK)     # ends at 630assert room.free() == ["m2"]assert refused(lambda: room.start("lee", "m1", Program.QUICK)) == "m1 is running"now = 630assert refused(lambda: room.empty("lee", "m1")) == "m1: wait for the owner"now = 645room.empty("lee", "m1")                     # 15 minutes later: allowedassert room.free() == ["m1", "m2"]

Lines 1 to 2

A clock we can move. Three quarters of an hour pass in no time.

1 of 5

Which cases to choose, and how to trace a race: verifying and extending a design.

Step 5b, minutes 36 to 45

Extend

What the extension touches

LaundryRoom+ start(who, id, program)+ empty(who, id)Machine+ start(...)+ empty(...)

1/4Before

The room and its machines. The limit was two lines in start.

owns (dies together)has (lives on)implements

Other follow-ups, and where they land

Follow-upChangesStays
Dryers with other programsMinutes become data per machine kindState rule, lock
Tell me when it is doneA scheduler beside the room, listenersMachine: the state is still computed
A broken machineA fourth state with an owner: the caretakerLimit, rules
Pay per washCharge before start, refund if start refusesMachine
Ten houses, one serverThe room per house, storage behind an interface, lock becomes a transactionRules and their tests

The last 60 seconds

  1. 1

    What works

    Start and empty keep three rules: one wash, limit, grace.

  2. 2

    What I left out

    Payment, faults, data on disk.

  3. 3

    What I would do next

    A message at the end of a wash, then storage.

Other lengths

35, 60 and 90 minutes

RoundAskNameSketchBuildProve
35 minutes4461011
45 minutes5581314
60 minutes66121818
90 minutes, must run87124518
When the code must run, most of the extra time goes to Build. Get one path running early.

Two habits

What keeps you on time

On time

  • Start and end of each step said aloud
  • The clock is visible
  • Ideas go to a parking list
  • The core path is coded first

Late

  • Questions until minute 12
  • Every class gets all its getters
  • A debate about a pattern name
  • The easy method first, the hard one never

Summary

The whole topic in one minute.

Ask 5, name 5, sketch 8, build 13, prove 14. End each step with one sentence and a result that can be seen.

Being late means cutting scope, never cutting proof. A small core that was traced beats a large one that was not.

  • Ask 5, name 5, sketch 8, build 13, prove 14.
  • Scale, actors, constraints. Then F and N.
  • Container, item, manager. Reject nouns aloud.
  • Patterns, structures and locks are chosen in the sketch, with a reason.
  • Build inside out, refusals first, time passed in.
  • One good case, one refusal, one race. Then one extension, and what stays.
  • Late? Cut scope, keep the proof.

Sources