Courses / Machine Coding and Low-Level Design in TypeScript / Chapter 1
Module 1 · The round · Chapter 1 of 28
The Machine Coding and LLD Round: Format, Scoring and a Method
Start here. Next up: Cornerstones of OOP in TypeScript: Encapsulation, Abstraction, Inheritance, Polymorphism.
Part 1 · Two rounds, one skill
Two kinds of design round
Companies that hire engineers often ask for a design round where you turn a short problem statement into classes and code. It comes in two forms, and this course prepares you for both.
A machine coding round gives you a problem such as a parking lot or a library and a fixed time. You write working code on your own machine, then demo it. A low-level design (LLD) round is a discussion. You clarify the problem, draw classes and relationships on a whiteboard or shared document, and sketch the key methods. Nothing has to run.
| Machine coding | LLD discussion | |
|---|---|---|
| You produce | Runnable code, a driver that exercises it | Diagrams, class and method sketches |
| Time | Often 90 minutes of coding plus a demo | Often 45 to 60 minutes |
| Judged on | Does it run, is it clean, does it handle bad input | Is the model sound, does it extend, can you explain it |
| Risk | Running out of time with half a system | Staying vague, drawing boxes with no behaviour |
Formats differ between companies, so treat the times above as typical, not fixed. One public description, a practice repository on GitHub written for one company's round, sets out three phases. The candidate gets 15 minutes to hear the problem and ask clarifying questions, 90 minutes to write executable code and send it, and 15 minutes to demo while the interviewer keys in several test cases and checks the output. During the coding phase the interviewer may hold one or two checkpoints. That is one published format, not a rule for every company.
Questions about the round itself
Before the problem arrives, it is fair to ask how the round works. The answers change how you spend the time, so ask the recruiter or the interviewer at the start.
- Which languages are allowed, and may you use your own editor and machine?
- Is internet access allowed for documentation, and are third-party libraries allowed, or only the standard library?
- Is in-memory storage acceptable, or is a database expected?
- How will the demo run: a command-line driver, tests, or input the interviewer types in?
- Will there be checkpoints during coding, and what is reviewed at each one?
In-memory storage and a command-line driver fit a 90-minute round, and every case in this course uses them. If the answer is that the interviewer types input during the demo, plan a small command reader on top of the driver, and keep the parsing out of the domain classes.
The same skill underneath
Both rounds test the same thing: turning vague requirements into a small, correct model of the world, then making that model do something. In the LLD round the model stays on paper. In the machine coding round the model becomes code and you must also prove it works.
That is why every case chapter in this course follows one spine: requirements, use cases, a class diagram, a flow, tested code and extensions. If you can build the code, the sketch for an LLD round is a subset of what you already did. If you only practise sketches, the first real coding round exposes everything you skipped.
The course uses TypeScript run directly on Node, so a case is a folder you can run and test with no build step. The next two chapters teach the object-oriented ideas and diagrams the cases lean on, and the chapters after them teach the principles and patterns reviewers expect you to name.
A first example: a canteen token queue
A canteen hands out numbered tokens. Customers take the next number and are served in order. The class below is the whole domain, and the driver after it is the demo a reviewer would watch.
export class TokenQueue { #next = 1; #waiting: number[] = []; issue(): number { const token = this.#next++; this.#waiting.push(token); return token; } serve(): number | undefined { return this.#waiting.shift(); } get length(): number { return this.#waiting.length; } }
queue.ts
import { TokenQueue } from './queue.ts'; const queue = new TokenQueue(); console.log('issued', queue.issue()); console.log('issued', queue.issue()); console.log('issued', queue.issue()); console.log('serving', queue.serve()); console.log('waiting', queue.length); console.log('serving', queue.serve()); console.log('serving', queue.serve()); console.log('serving', queue.serve());
demo.ts
issued 1 issued 2 issued 3 serving 1 waiting 2 serving 2 serving 3 serving undefined
Output of node demo.ts
The queue keeps its state in #-private fields, so callers can only issue and serve. That is the shape every case will have: a small domain, and a driver that shows it working. One flaw is already visible. When nobody is waiting, the last call printed serving undefined. The next lesson fixes that.
What does a machine coding round produce that an LLD discussion does not?
- Working, runnable code that the reviewer can execute.
- An LLD discussion stops at diagrams and sketched methods.
Is "15 minutes clarifying, 90 coding, 15 demo" the format every company uses?
- No. It is one published description of one company's round.
- Treat timings as typical and ask for the real ones when you are invited.
Diagnose: in the demo, an empty queue prints serving undefined and the program carries on. What would a reviewer conclude?
- That illegal actions are not handled: the program gives a silent wrong answer instead of a clear refusal.
Part 2 · What reviewers score
The criteria
A reviewer reads your code with a checklist. The same published description lists four criteria: code hygiene, functional correctness and completeness, language proficiency, and error handling. Hygiene is further described as readability, modularity and testability, and language proficiency as using the right language constructs where they apply.
Tests belong under hygiene in that description, so the table lists them on their own row. This course adds one criterion of its own, because every case chapter ends with it: extensibility, meaning how many files change when a new requirement arrives. Treat the rest as published and extensibility as this course's own practice. It makes the published criteria easier to show: a small change proves modularity, and your own tests prove correctness.
| Criterion | A reviewer looks for | A sign of trouble |
|---|---|---|
| Readability | Names that say what things are, short methods | Names like data, temp, process |
| Modularity | Small classes with one reason to change | One 400-line class that does everything |
| Correctness | The listed use cases work, edge cases included | Works for the demo input only |
| Completeness | Everything in scope is done, nothing half-built | Three features started, none finished |
| Language use | Idiomatic code, the right data structure | Arrays searched by hand where a Map fits |
| Error handling | Bad input and illegal actions are rejected clearly |
Error handling in practice
Error handling is easy to lose marks on, because the happy path demo passes without it. Two habits cover most of it. First, validate input where it enters the system: a constructor that refuses a capacity of zero never lets a broken object exist. Second, signal illegal actions with a domain error, an error class specific to your problem, carrying a short code that callers and tests can check.
A string code from a fixed union such as 'EMPTY' | 'FULL' is better than matching on message text, because tests do not break when someone rewords a message, and the compiler stops a typo in the code.
Compare with the first queue. Serving an empty queue returned undefined. The caller has to remember to check, and if they forget, undefined flows on into later code and fails somewhere far away. Throwing at the point of the mistake keeps the failure next to its cause.
The same code after validation
The error class first, then the queue with a validated capacity and two throwing paths.
export type QueueErrorCode = 'EMPTY' | 'FULL'; export class QueueError extends Error { readonly code: QueueErrorCode; constructor(code: QueueErrorCode, message: string) { super(message); this.name = 'QueueError'; this.code = code; } }
errors.ts
import { QueueError } from './errors.ts'; export class TokenQueue { #next = 1; #waiting: number[] = []; readonly #capacity: number; constructor(capacity: number) { if (!Number.isInteger(capacity) || capacity < 1) { throw new RangeError('capacity must be a positive integer'); } this.#capacity = capacity; } issue(): number { if (this.#waiting.length === this.#capacity) { throw new QueueError('FULL', `queue holds ${this.#capacity}`); } const token = this.#next++; this.#waiting.push(token); return token; } serve(): number { const token = this.#waiting.shift(); if (token === undefined) throw new QueueError('EMPTY', 'no tokens'); return token; } }
queue.ts
serve now returns number, not number | undefined, so callers no longer need a check. The FULL rule is a new requirement, and it touched only this class.
Running the demo
import { TokenQueue } from './queue.ts'; import { QueueError } from './errors.ts'; const queue = new TokenQueue(2); queue.issue(); queue.issue(); for (const action of [() => queue.issue(), () => queue.serve()]) { try { console.log('ok', action()); } catch (e) { if (!(e instanceof QueueError)) throw e; console.log(e.code, '-', e.message); } } queue.serve(); try { queue.serve(); } catch (e) { if (e instanceof QueueError) console.log(e.code, '-', e.message); }
demo.ts
FULL - queue holds 2 ok 1 EMPTY - no tokens
Output of node demo.ts
Each illegal action is rejected with its own code. The demo catches only QueueError and rethrows anything else with throw e, so a genuine bug is never hidden behind the handler.
Common deductions
Most lost marks come from a few habits that are easy to avoid once you know them. Each row below breaks one of the criteria above.
| Habit | Why it costs marks | Instead |
|---|---|---|
console.log inside domain classes | The class cannot be tested or reused without printing | Return values; let the driver print |
| A catch block that logs and carries on | A real bug looks like success | Catch only your own error class, rethrow the rest |
Magic numbers such as 10 or 0.18 in methods | The reader cannot tell what the number means | A named constant, or a value passed in |
| Module-level mutable state | Tests interfere with each other | State inside objects that tests create fresh |
The same switch on a type field in many methods | Every new kind edits each of those methods | One class per kind behind a shared interface, when new kinds are likely |
None of these needs extra time to avoid. They need a decision at the moment you write the line, which is why it pays to rehearse them before the round.
Why throw a QueueError with a code instead of returning undefined from serve?
- The failure surfaces at the mistake, not later in unrelated code.
- Tests and callers can branch on
code, which is stable, unlike message text.
Which criteria did adding the FULL rule improve?
Part 3 · A method for any prompt
Seven steps
Without a method, it is easy to start typing classes in the first minute and discover the real requirements at minute sixty. The method below is the order this course uses in every case chapter. Each step produces something you can show.
- 1Clarifyask questions, write Must, Should and Out of scope
- 2Use caseswho does what, as a short list
- 3Classesnouns become classes, verbs become methods
- 4Core flowone sequence or state diagram of the main path
- 5Code in layersdomain, storage, services, with a driver that calls them
- 6Teststhe core and the edges
- 7Extensionsadd one new requirement and count the files that change
Clarifying comes first because the statement is deliberately short. Ask about scale only when it changes the design, ask what is out of scope, and write the answers down where the reviewer can see them. The approach chapter later in this course walks through the steps on one example. It folds writing tests into building each layer, so it counts six.
For the canteen queue, the notes after clarifying could read: Must, issue a token and serve the next one in order; Should, a limit on waiting tokens; Out of scope, payment, menus and several counters. Three lines like these settle what done means before any code exists, and the reviewer can correct a wrong guess in seconds.
Planning the time
Decide the time split before you start. These plans are our suggestion, not a standard. They keep coding to the middle and leave room to test.
| 90-minute machine coding | Minutes | 45-minute LLD discussion | Minutes |
|---|---|---|---|
| Model and use cases | 10 | Clarify and scope | 5 |
| Domain classes | 20 | Use cases | 5 |
| Services and storage | 25 | Class diagram | 12 |
| Driver and demo | 10 | Core flow diagram | 10 |
| Tests | 15 | Key methods sketched | 8 |
| Extension and buffer | 10 | Extensions and trade-offs | 5 |
Minutes10
45-minute LLD discussionClarify and scope
Minutes5
Minutes
The method as a pipeline
The scene follows one prompt through the steps. The change to watch is the last one, a requirement that arrives after the first demo.
Watch for the late requirement going back to the model, not straight to the code
Read it as steps
A prompt moves through clarifying, the model, code, tests and a demo; a late requirement returns to the model
The late rule did not go to the code. It went back to the model, and the code and tests followed. Doing it the other way leaves a model that no longer matches the program, and the next change is harder.
Project setup and a first test
Set up the project in the first two minutes so tests are never an afterthought. Every code sample in this course was run on Node 24.18, and readers need Node 22.18 or later so that .ts files run without flags.
mkdir canteen && cd canteen npm init -y npm i -D typescript@7.0.2 @types/node@24
Run once, then edit package.json
{
"type": "module",
"private": true,
"scripts": {
"test": "node --test",
"check": "tsc -p ."
},
"devDependencies": {
"@types/node": "^24.19.2",
"typescript": "^7.0.2"
}
}package.json
{
"compilerOptions": {
"noEmit": true,
"target": "esnext",
"module": "nodenext",
"rewriteRelativeImportExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"strict": true,
"types": ["node"]
},
"include": ["**/*.ts"]
}tsconfig.json
Your first test run
The test script is just node --test, Node's built-in runner. It finds files named *.test.ts on its own. Here are three tests for the validated queue of the previous lesson, then the run.
import { test } from 'node:test'; import assert from 'node:assert/strict'; import { TokenQueue } from './queue.ts'; test('tokens are served in the order they were issued', () => { const queue = new TokenQueue(3); queue.issue(); queue.issue(); assert.equal(queue.serve(), 1); assert.equal(queue.serve(), 2); }); test('serving an empty queue throws EMPTY', () => { const queue = new TokenQueue(3); assert.throws(() => queue.serve(), { code: 'EMPTY' }); }); test('a full queue refuses the next token', () => { const queue = new TokenQueue(1); queue.issue(); assert.throws(() => queue.issue(), { code: 'FULL' }); });
queue.test.ts
✔ tokens are served in the order they were issued (0.5805ms) ✔ serving an empty queue throws EMPTY (0.4462ms) ✔ a full queue refuses the next token (0.1189ms) ℹ tests 3 ℹ suites 0 ℹ pass 3 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 102.5162
Output of node --test (timings vary)
Why plan minutes for tests inside the 90?
- Tests are scored, and written last they are the first thing cut under time pressure.
What do you do first when a prompt arrives?
- Clarify: ask questions and write Must, Should and Out of scope.
- Coding first means discovering requirements late.
A late requirement arrives during the demo. Where does your change start?
- In the model, then the code and tests that follow from it, as the scene showed.
Part 4 · TypeScript on Node for the round
Types are erased, not checked
Node can run .ts files directly. It does this by type stripping: it removes the type annotations and runs what is left as JavaScript. The feature is on by default from Node 22.18 and stable from 24.12. Because the types are only removed, Node never checks them, and it ignores tsconfig.json. A program with a wrong type still runs.
const count: number = 'three'; console.log(count);
bad-types.ts
three
node bad-types.ts
The type checker is the separate tsc program. Run it as part of your check script, and treat its errors as bugs even though Node would run the file.
bad-types.ts(1,7): error TS2322: Type 'string' is not assignable to type 'number'.
npx tsc, wrapped to fit
Syntax that cannot be erased
Stripping only works for syntax that disappears cleanly. A few TypeScript features generate code, so Node refuses them. The main ones are enum, a constructor parameter property such as constructor(public id: number), namespaces that contain code, and decorators. Rejected syntax raises an error when the file loads, so you find out at once. Decorators fail differently, as a plain parser error, because Node does not transform them at all.
enum Status {
Waiting,
Served,
}
console.log(Status.Served);bad-enum.ts
SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only mode
node bad-enum.ts (first line of the error), wrapped to fit
class Ticket { constructor(public id: number) {} } console.log(new Ticket(7).id);
bad-param.ts
SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript parameter property is not supported in strip-only mode
node bad-param.ts (first line of the error), wrapped to fit
Setting erasableSyntaxOnly in tsconfig.json makes tsc report these as errors too, so you learn about them before running. Node also has an --experimental-transform-types flag that turns some of this syntax into JavaScript. This course does not use it: it is experimental, and code that needs no transform runs the same everywhere.
bad-enum.ts(1,6): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled.
npx tsc, wrapped to fit
The replacements
Use a string-literal union built from an as const array in place of an enum. You get a type for the compiler and a real array for loops, with nothing to strip. Use ordinary fields and an assignment in the constructor in place of a parameter property. Use #name for private state: it is hard-private at run time, while the private keyword only exists for the compiler.
export const STATUSES = ['waiting', 'served'] as const; export type Status = (typeof STATUSES)[number]; export function label(status: Status): string { return status === 'waiting' ? 'Please wait' : 'Collect your meal'; }
status.ts
Two more rules keep imports working. Relative imports must name the file with its .ts extension. And a name that is only a type must be imported with import type, because the stripper cannot tell a type from a value and would leave a real import behind.
import { STATUSES, label } from './status.ts'; import type { Status } from './status.ts'; const now: Status = 'waiting'; console.log(STATUSES, label(now));
use-status.ts
[ 'waiting', 'served' ] Please wait
node use-status.ts
The import mistake
Leave out type and Node loads the module and looks for a value named Status, which does not exist.
import { Status } from './status.ts'; const now: Status = 'waiting'; console.log(now);
bad-import.ts
SyntaxError: The requested module './status.ts' does not provide an export named 'Status'
node bad-import.ts (first line of the error), wrapped to fit
With verbatimModuleSyntax on, tsc catches it first: error TS1484: 'Status' is a type and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled. The tsconfig.json of the previous lesson turns on both flags, and npx tsc -p . printing nothing is the signal that all is well. The same flags are set in every chapter's project, so the code samples in this course are always valid in that mode.
These compiler options are not our invention. The Node documentation on TypeScript recommends the same set for code that Node runs directly: noEmit, target esnext, module nodenext, rewriteRelativeImportExtensions, erasableSyntaxOnly and verbatimModuleSyntax. This course adds strict, and types set to node so that tsc knows modules such as node:test.
If a round allows only JavaScript, nothing in this course changes except the annotations. Delete the types and the classes, tests and drivers run as they are. The habits that matter, # fields, as const arrays of allowed values and small domain errors, are plain JavaScript; only the annotations go.
Check yourself
Node ran a file that assigns a string to a number. Why?
- Node strips types without checking them. Only
tscreports the error.
What replaces an enum when only erasable syntax is allowed?
- A string-literal union derived from an
as constarray.
Why is import type needed for a name that is only a type?
- The stripper cannot tell types from values, so a plain import is kept and fails at run time.
Part 5 · Study plan
Before you start
Practise a problem on your own first, under the clock, before you read a worked solution. Reading a solution feels like learning, but only writing one shows you which step you skip. The method in this chapter is what you rehearse, so time each step.
After each attempt, review against the criteria table from earlier. Mark each row as met, partly met or missed. Misses repeat across problems, and the pattern tells you what to practise next: often error handling, tests or time.
Run every sample in this course yourself. Type it rather than paste it at least once for each new idea. A class you have typed is one you can write again under time pressure.
A three-week and a six-week plan
Both plans assume about an hour a day. The numbers in brackets are the reading minutes of the chapters listed, so the time you spend building each problem yourself comes on top. In the three-week plan you already write TypeScript comfortably and want to move fast. In the six-week plan you spend more time on the object-oriented chapters first.
| Week | Three-week plan (reading minutes) | Six-week plan (reading minutes) |
|---|---|---|
| 1 | OOP cornerstones, object-oriented design, principles (99) | OOP cornerstones, object-oriented design (64) |
| 2 | Patterns, the approach chapter, parking lot, elevator, library (164) | Principles, patterns (73) |
| 3 | Three more cases of your choice (about 30 each); one timed mock prompt | Design approach, parking lot (64) |
| 4 | Not used | Elevator, library, vending machine (90) |
| 5 | Not used | Movie tickets, chess, online shopping (109) |
| 6 | Not used | Stock brokerage, then the mock chapter, timed (66) |
Pick later cases by the kind of product the team you are applying to builds. Booking and scheduling problems lean on time ranges and concurrency. Game and simulation problems lean on state and rules. Whatever you choose, finish with the mock chapter at the end of the course, under the clock.
Practising one problem
- Read the prompt and set a timer for the time plan you chose.
- Spend the clarifying time writing Must, Should and Out of scope. Do not code yet.
- Write use cases, then a class list, then one flow diagram.
- Write the driver's calls first to fix the public names, then code the domain and services until it runs, then the tests.
- Stop at the timer, even if unfinished. Note what was missing.
- Score yourself against the criteria table, then read the chapter and compare the model, not the code line by line.
- Redo the weakest step a day later.
LeetCode has small class-design problems, such as Design Parking System and LRU Cache. They are far smaller than a machine coding prompt, but they make good 20-minute warm-ups for one class with a clear contract and edge cases.
Practising the discussion round
The LLD discussion needs its own practice, because the skill is explaining while you draw. Ask a friend to play the interviewer, or record yourself. Set 45 minutes, follow the right-hand column of the time plan, and say each decision aloud with its reason, such as: a booking is an entity because its status changes while its id stays the same.
Expect questions that test the model rather than the syntax. What happens if two people book the last slot at once? Which class changes if prices depend on the day of the week? Where would you add a second payment method? Practise answering by pointing at a class on your diagram and naming the one change. If the answer needs several classes to change, note it as a weakness of the model to fix next time.
Alternate the two kinds of practice. One week, code a case in 90 minutes; the next, discuss a different case in 45. Both rounds draw on the same model, so each kind of practice improves the other.
| Term | Meaning |
|---|---|
| Machine coding round | A timed round where you write working code for a design problem and demo it |
| LLD round | Low-level design: a discussion of classes, relationships and key methods, with nothing run |
| Driver | A small script that calls the code to play the use cases and prints what happens |
| Domain error | An error class specific to the problem, carrying a short code that tests can check |
| Must, Should, Out of scope | What you build, what you add if time allows, and what you leave out on purpose |
| Type stripping | Running TypeScript by deleting the type annotations, with no type checking |
| Erasable syntax | TypeScript syntax that disappears when types are deleted, leaving valid JavaScript |