AlgoViz

Problem analyzer

medium 45 min

Eight questions that turn any prompt into a design skeleton in about six minutes: verbs, container, item, manager, policy, lifecycle, speed and sharing.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:39

Eight questions for any prompt

1:00Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A problem analyzer here is not a tool that thinks for you. It is a fixed list of questions, always asked in the same order, with one line written for each answer. The list makes sure that nothing important is forgotten while you are nervous.

The middle five have an old short name, C.I.M.P.L., which sounds like simple: Container, Item, Manager, Policy, Lifecycle. We put verbs in front, because a class without a call is decoration. We put speed and sharing behind, because they choose the containers and the locks.

The answers map to decisions. Policies with several forms suggest Strategy. Lifecycles suggest a table of moves or State. Speed picks the data structure. Sharing picks the lock. The mapping is a suggestion that each answer must earn.

Why it exists

The first six minutes decide the round. People who start drawing at once often forget one of two things: what varies, or what two users do at the same moment.

A repeatable list also frees your head. You do not think about what to think about. And the interviewer can follow, because you say the question aloud before you answer it.

Lists have a danger: filling them without thinking. That is why each line must end in a decision or in the words not needed here.

A short history

  1. 1935

    After the crash of the Boeing Model 299, the prototype of the B-17, checklists became part of flying. It is the story most often told about their beginning.

  2. 1945

    George Polya publishes How to Solve It: understand the problem, make a plan, carry it out, look back. A list of questions for mathematics.

  3. 1989

    Kent Beck and Ward Cunningham present CRC cards at OOPSLA: one card for each class, with its responsibilities and collaborators.

  4. 1992

    Ivar Jacobson and colleagues publish a method driven by use cases, with entity, interface and control objects. Start from what users do.

  5. 2008

    The World Health Organization publishes a surgical safety checklist, used before an operation begins, before the cut, and before the patient leaves.

Words to know

Verb
A call from outside: park, lend, move a piece.
Container
What holds the things.
Item
A thing with an identity that is managed.
Manager
The object that receives verbs and keeps the rules between items.
Policy
A rule that may have several forms.
Lifecycle
The phases of one item and the allowed moves.
Speed
The call that must be fast, and how many items there are.
Sharing
What two callers could touch at the same time.
Gap
A question without an answer. Ask it, or state an assumption.

How it works

Step through the idea, or press Play.

Step 1 of 4

Verbs. Who calls what?

Understand it

Start here

The toy doctor's checklist

Lee repairs toys. All toys are different, and the checklist on Lee's board is always the same. It has eight boxes.

Doctor Lee and the robot

The toys change, the list does not.

The list

Eight questions and what each decides

The analyzer

LetterAskDecidesIf there is no answer
V verbsWho calls, and what do they want?Public methodsStop and ask. Nothing works without it
C containerWhat holds the things?Owner of the collectionOne map inside the manager
I itemWhat has an identity and changes?Entity classesPerhaps it is only a value
M managerWho keeps rules between items?The class with the verbsThe container may be enough
P policyWhich rule has or will get several forms?Strategy, function, or a tablePlain code
L lifecycleWhich phases, which moves, which are forbidden?Table of moves, or StateNo status field
S speedWhich call is hot, with how many items?Data structureA list, and say so
S sharingWhat can two callers touch at once?Lock, semaphore, queue, transactionSingle thread, said aloud
The first four are one minute each, the last four half a minute each: six minutes.

The order, and where you go back

One picture for C.I.M.P.L.

  • Container

    A box.

  • Item

    The things in the box.

  • Manager

    Somebody stands beside the box and takes requests.

  • Policy

    The rule book in their hand. It can be exchanged.

  • Lifecycle

    The conveyor belt that carries each thing from phase to phase.

Details of the first rows have their own pages: requirements, entities and owners, class design. How much time each part gets is in the execution flow.

Prompt 1

Parking lot

Design a parking lot

QuestionAnswerDecision
Verbsenter, pay, leaveParkingSystem with three methods, used by gates
ContainerLot, floors, spotsLot owns spots. A floor is only a number unless it has rules
ItemSpot, ticket, vehicleTicket and spot have identity. Car and bike differ in size, so vehicle is a value
ManagerParkingSystem behind entrance and exit gatesGates are callers, not owners
PolicyPrice: hourly, flat, weekend. Spot: nearest, randomPrice is Strategy. Spot choice is a function
LifecycleSpot: free, taken, free. Ticket: issued, paid, leftSmall tables of moves
SpeedNearest free spot per size, ticket by numberHeap or bit set per size, map for tickets
SharingTwo gates, one last spotOne lock around find and take. A semaphore alone does not say which spot
The full design: parking lot.

Prompt 2

Elevator

Design an elevator system

QuestionAnswerDecision
Verbscall from a floor, choose a floor, one step of timeDispatcher and Car
ContainerBuilding with cars. Shaft and floor are numbersNo class for a number
ItemCar, request. A button is an eventRequest has floor and direction
ManagerDispatcher picks the car, the car plans its stopsTwo owners, two rules
PolicyWhich car: nearest, least busy, by destination. Stop order: SCAN or LOOKStrategy for the dispatcher
LifecycleCar: idle, up, down, doors open, out of serviceState. Up to down goes through a stop, never directly
SpeedNext stop above or belowTwo sorted sets of floors
SharingButtons and the moving car change the stopsOne worker per car, requests through a queue
The full design: elevator.

Lifecycle of a car

Display boards listen to floor changes. That is Observer, and only if there is more than one kind of listener.

Prompt 3

LRU cache

Design an LRU cache

QuestionAnswerDecision
Verbsget, putTwo methods, both must be O(1)
ContainerThe cache itselfA hash map is how, not what
ItemEntry with key and valueA node, private
ManagerNone besides the cacheDo not invent a CacheService
PolicyEviction: LRU, LFU, FIFO. Expiry by timeStrategy only if it may be exchanged. Expiry as Decorator
LifecycleEntry: present, evicted. Nothing moreNo State. Cold, warm and full are words about the cache, not phases with rules
SpeedLookup and move to frontHash map plus doubly linked list
Sharingget changes the orderOne lock. A read-write lock does not help
The full design: LRU cache.

Prompt 4

Chess

Design a chess game

QuestionAnswerDecision
Verbsmove, resign, undo, showGame is the door
ContainerBoard, 8 by 82D array. A square is a pair of numbers
ItemPiece: king, queen, rook, bishop, knight, pawn. MovePieces behave differently, so here subclasses are right
ManagerGame for turns, a rules object for checkA piece knows its steps. It does not know check
PolicyHow a piece moves, how a computer scoresPolymorphic pieces. Scoring only if there is a computer player
LifecycleSetup, in progress, ended by mate, draw or resignation. Turn: white, blackCheck is a fact about a position, not a phase
SpeedPiece on a square, last moveArray and a stack of moves for undo
SharingTwo players take turnsNothing until online play. Then one queue for matching
The full design: chess. Undo is the force for Command. Flyweight fits shared pictures only. A common check around each piece's own rule is a Template method.

Prompt 5

Vending machine

Design a vending machine

QuestionAnswerDecision
Verbsinsert, select, cancel, refillMachine is the door
ContainerMachine, slots with productsMap from code to slot
ItemProduct, slot, saleA coin is a value
ManagerThe machine, with a payment partPayment behind one method
PolicyCash, card, phone. Refund ruleStrategy for payment
LifecycleMachine: idle, has money, dispensing. Sold out belongs to a slot, not to the machineState, because select means something else in each
SpeedProduct by codeMap. Sales in an append-only list
SharingButtons, sensor and phone appOne event at a time
The full design: vending machine.

Side by side

The same list, five shapes

Where each problem is heavy

ProblemHeavy lineLight lineFirst class to write
Parking lotSpeed and sharingLifecycleSpots
ElevatorLifecycle and policyItemCar
LRU cacheSpeedManager, lifecycleThe cache with its list
ChessPolicy: how pieces moveSharingBoard and one piece
Vending machineLifecycleContainerMachine and its states
Spend your minutes on the heavy line. That is the part the interviewer wants to see.

A line that helps

  • Policy: price, three forms today, so a function per form
  • Lifecycle: none, an entry is there or not
  • Sharing: two gates, one last spot, lock around find and take

A line that fills space

  • Policy: Strategy pattern
  • Lifecycle: created, updated, deleted
  • Sharing: thread safe

Keywords

A program that asks, instead of answering

A program can look for words in a prompt. But words answer nothing. A naive search even finds words inside words: one is in phone and add is in address. So our analyzer does two modest things: it turns whole words into questions, and it reports gaps in your own answers.

From a word to a decision

The word is only the first box. Two questions stand between it and a pattern. The words for each pattern are on the matrix page.

The analyzer in code

Substrings give patterns for words that are not there.

NAIVE = {    "Singleton": ["single", "one", "global"],    "Decorator": ["add", "wrap", "extend"],}def naive(prompt):    text = prompt.lower()    return [name for name, words in NAIVE.items() if any(w in text for w in words)]assert naive("Design a phone address book") == ["Singleton", "Decorator"]

Line 9

w in text looks inside words. This is the bug, and it is a small copy of what people do when they hear one word and name a pattern.

1 of 2

A new prompt

The charging shelf: never seen before

The prompt: a library lends tablets from a shelf with 12 charging slots. A reader may have one tablet at a time. Hand out the fullest one. Tablets come back to any free slot. Broken ones are taken out. Try the eight lines yourself before you look.

Eight lines in six minutes

QuestionAnswerDecision
Verbslend, give back, report brokenThree methods
ContainerShelf with 12 slotsA slot is only a place: the shelf counts
ItemTablet with number, battery and phaseOne entity. Reader is an id
ManagerDeskKeeps the rule of one per reader
PolicyFullest now, least used was mentioned as an ideaA function parameter, no class
Lifecyclecharging, out, brokenTable of four moves
SpeedFullest of 12, a few times an hourA loop. Battery changes all the time, so a heap would be wrong as well
SharingTwo librarians at two screensOne lock around the three methods

Every noun a class

Library+ getShelf(): ShelfShelf+ getSlots(): ListSlot+ getTablet(): TabletTablet+ battery: int

1/3Nouns from the prompt

Library, shelf, slot, tablet. A chain where each only returns the next.

owns (dies together)has (lives on)uses

Six classes, no behaviour.

From the eight lines

TabletDesk- tablets: Map<int, Tablet>- holders: Map<reader, int>+ lend(reader): int+ giveBack(reader, battery)+ broken(number)

1/3Verbs on the desk

The three verbs become three methods of the manager.

owns (dies together)uses

Four boxes, and the two small ones are an enum and a function.

Charging shelf, from the eight lines

The L line, written as data.

import threadingfrom dataclasses import dataclassMOVES = {    ("charging", "lend"): "out",    ("out", "give back"): "charging",    ("charging", "break"): "broken",    ("out", "break"): "broken",}@dataclassclass Tablet:    number: int    battery: int    phase: str = "charging"    def fire(self, event):        if (self.phase, event) not in MOVES:            raise ValueError(f"cannot {event} tablet {self.number}, it is {self.phase}")        self.phase = MOVES[(self.phase, event)]

Lines 4 to 9

Four moves from the eight lines. Broken has no way out, so it is the last phase.

1 of 2

The lend call

Quick drill

Two prompts in five words

Cover the right side and say C, I, M, P and L for both. Then add the verbs and the two S.

Library and food delivery

LetterLibrary managementOnline food delivery
Vborrow, return, searchorder, accept, pick up, deliver
CShelf and section: the catalogueThe restaurant's menu
IBook copy, member, loanOrder, dish, courier
MLibrarian, better: lending deskOrderService
PLending rulesPrice, choice of courier
LOn shelf, borrowed, returnedPlaced, accepted, picked up, delivered
S speedCopy by number, title searchOpen orders of a restaurant
S sharingLast copy, two membersTwo couriers, one order
More on both kinds: library and ride sharing, which has the same matching.

When the prompt gives you nothing

  1. 1

    What holds the resources?

    Start with one map from id to item.

  2. 2

    What is handled?

    The thing that would get a number on a paper form.

  3. 3

    Who controls?

    The desk where a person would ask.

  4. 4

    What can vary?

    Ask: which rule did you change last?

  5. 5

    What phases?

    Ask: how does one of these end?

  6. 6

    Several threads?

    Ask: who else can press a button now?

Summary

The whole topic in one minute.

Ask eight questions in order: verbs, container, item, manager, policy, lifecycle, speed, sharing. Write one line for each, ending in a decision or in not needed.

The answers give classes, the rule that varies, the table of moves, the containers and the lock. Keywords only tell you what to ask.

Look back at the end: every verb has an owner, every item has a first and a last phase, every shared thing has a guard.

  • Verbs, container, item, manager, policy, lifecycle, speed, sharing.
  • Every line ends in a decision or in not needed.
  • Words in the prompt give questions, never patterns.
  • One form of a rule is plain code.
  • Check is a fact, not a phase. Sold out belongs to a slot.
  • Find the heavy line and spend your time there.
  • Look back: owners, first and last phase, guards.

Sources