Machine Coding Rounds
A machine-coding round asks a simple question with an unforgiving test: can you build a small, well-structured program that actually runs, in the time available? You get a problem statement (usually half a page to a page of requirements), your own IDE or an online one, and somewhere between 60 and 120 minutes. At the end there's a demo, a code review, or both. Unlike a whiteboard LLD round, "I'd do X here" counts for very little. The code either does X or it doesn't.
This page covers the format, a time plan, a project layout you can type from memory, the four building blocks of almost every solution (models, in-memory repositories, a service layer and a driver), how to handle validation and errors without drowning in them, and how to write a handful of useful tests in ten minutes. It ends with a complete worked solution, an expense-sharing ledger, in Java, Python and TypeScript, plus a checklist to run before you say "done".
What the format looks like
The details vary, but most machine-coding rounds share a shape.
- Problem statement. A concrete, bounded problem: a parking lot, a ride-booking core, an expense splitter, a snake-and-ladders game, a rate limiter, an in-memory key-value store. It has explicit commands or operations, and often sample input and expected output.
- Build time. Usually 60–90 minutes, sometimes up to 120. The interviewer may stay on the call, drop off and come back, or check in every 20–30 minutes.
- Demo. You run the program against the sample input, and sometimes against inputs the interviewer types live.
- Review. The interviewer reads the code and asks why it's structured this way, how you'd add a feature, what happens on bad input, and how you'd make it thread-safe. Often there's an extension to implement live in the last 10–15 minutes.
Some details matter a lot:
- No database, no framework, no network. Almost every machine-coding prompt says "in-memory" explicitly. If it doesn't, ask, and then assume in-memory. Spending 15 minutes wiring a web framework is one of the most common ways to fail.
- Input is usually commands. Either a text file or stdin with one command per line, or a set of method calls in a
main. Ask which the interviewer prefers. If they don't mind, use a command-line driver that reads lines, because it makes the demo trivial. - "Runs" means it compiles, executes the sample and prints sensible output. Partial features that run are worth far more than complete features that don't compile.
Ask these four questions in the first five minutes
- "Should input come from a file or stdin, or is a
mainwith hard-coded calls fine?" - "Is the output format in the statement exact, or illustrative?"
- "Which features are must-haves, and which are optional if time allows?"
- "Do you want tests, or is a driver that exercises the sample enough?"
The answers decide where your 90 minutes go.
How it's scored
The scoring page covers this in detail. In short, for machine coding the weighting shifts toward:
| Weighted heavily | Weighted lightly |
|---|---|
| The program runs and handles the sample input | Diagrams |
| Clean separation: models, storage, services, driver | Exhaustive pattern vocabulary |
| Validation with clear error messages | Performance tuning |
| Readable, consistent names and structure | Every optional feature |
| Ease of adding the live extension | Clever one-liners |
| A few tests or assertions | 100% test coverage |
The live extension is often the deciding moment. If the interviewer says "now add a percentage split" and it takes you three minutes because there's a SplitStrategy interface, that's a strong signal. If it takes twenty because the split logic is tangled into the input parser, the earlier 80 minutes are judged in that light.
A time plan for 90 minutes
| Minutes | Phase | Output | Rule |
|---|---|---|---|
| 0–8 | Read and clarify | Assumptions written as a comment block at the top of Main or in a README | Don't type code yet |
| 8–18 | Model and skeleton | Packages, model classes, empty service, a main that compiles and prints "ok" | Compile by minute 18 |
| 18–50 | Core features | Service methods for the must-have commands, the driver parsing each command | Run the sample after every feature |
| 50–62 | Validation and errors | Custom exceptions, input checks, the driver printing errors without crashing | Bad input never crashes the program |
| 62–74 | Tests | Five to eight focused tests on the core rules | Test rules, not getters |
| 74–82 | Optional features or cleanup | One extra feature or renaming and tidying | Don't start a feature you can't finish |
| 82–90 | Demo prep | Sample run, a short "design notes" comment, known gaps listed | Stop coding at 85 |
For 60 minutes, compress proportionally: clarify 5, skeleton 7, core 25, validation 8, tests 8, demo 7. Tests and validation shrink but don't vanish. For 120 minutes, the extra time goes to core features (+15) and tests (+10), and the rest to one optional feature.
flowchart LR
R["Read and clarify<br/>0-8"] --> K["Skeleton compiles<br/>8-18"]
K --> F["Feature loop<br/>18-50"]
F -->|"run sample"| F
F --> V["Validation<br/>50-62"]
V --> T["Tests<br/>62-74"]
T --> X["Extra or tidy<br/>74-82"]
X --> D["Demo<br/>82-90"]
The feature loop
From minute 18 onwards, work in a tight loop: pick one command, implement it through all layers, run the driver, see the output, commit if you're using git, repeat. Don't write all the models, then all the services, then all the parsing. That approach has nothing runnable until minute 60, and if time runs out you have three half-layers and no feature.
Hard stops
Put two hard stops in your head. Minute 18: it compiles. Minute 85: you stop adding code. If you miss the first, cut scope immediately. If you ignore the second, you'll be debugging a compile error during the demo.
The project skeleton
You'll type the same skeleton in every round, so practise it until it takes under five minutes. Here's the shape for the worked example below, in each language.
expense-ledger/
src/main/java/ledger/
Main.java driver: reads commands, prints results
cli/CommandRunner.java parses one line, calls the service
model/User.java
model/Expense.java
model/Money.java parse and format integer cents
split/SplitStrategy.java interface
split/EqualSplit.java
split/ExactSplit.java
split/PercentSplit.java
repo/UserRepository.java interface + InMemoryUserRepository.java
repo/ExpenseRepository.java interface + InMemoryExpenseRepository.java
service/BalanceSheet.java
service/ExpenseService.java
error/ValidationException.java
error/NotFoundException.java
src/test/java/ledger/ExpenseTests.java
expense_ledger/
main.py driver
ledger/
cli.py CommandRunner
model.py User, Expense, money helpers
split.py EqualSplit, ExactSplit, PercentSplit
repo.py InMemoryUserRepository, InMemoryExpenseRepository
service.py BalanceSheet, ExpenseService
errors.py ValidationError, NotFoundError
tests/test_ledger.py
expense-ledger/
src/
main.ts driver
cli.ts CommandRunner
model.ts User, Expense, money helpers
split.ts strategies
repo.ts interfaces + in-memory implementations
service.ts BalanceSheet, ExpenseService
errors.ts
test/ledger.test.ts node:test
package.json, tsconfig.json
The layer boundaries matter more than the file count. In a real round, splitting into files like this costs a minute or two and makes the review much easier. For this page, each language's solution is one file with section comments that mark where each file would start, so you can copy and run it directly.
The four building blocks
flowchart TD
D["Driver: main + CommandRunner"] -->|"parsed arguments"| S["ExpenseService"]
S --> ST["SplitStrategy implementations"]
S --> B["BalanceSheet"]
S --> UR["UserRepository"]
S --> ER["ExpenseRepository"]
UR --> M["Model: User, Expense"]
ER --> M
- Models are plain classes or records holding the domain data:
User,Expense. Keep them small and immutable where you can. If a model has a rule that only touches its own fields, the rule goes on the model. - Repositories store and fetch models. In a machine-coding round they're in-memory: a
HashMapordictbehind a small interface. The interface is there because almost every reviewer asks "how would you switch to a database?", and "implementUserRepositoryagainst the database" is a one-sentence answer. See the repository pattern. - The service layer holds the use cases: add a user, record an expense, settle up, show balances. It validates input, coordinates the repositories and domain objects, and is the only layer that changes state. This is where most of your time goes.
- The driver turns text into service calls and results into text. It knows the command syntax and the output format, and nothing about business rules. Keeping parsing out of the service is what makes the service testable, and it lets you replace the CLI with a REST controller later without touching the logic.
Wire it by hand
Create the objects in main and pass dependencies through constructors:
ExpenseService service = new ExpenseService(
new InMemoryUserRepository(), new InMemoryExpenseRepository(), strategies);
There's no dependency-injection container, and no singletons. Hand wiring takes three lines, makes tests easy (they build their own service), and avoids the static-singleton trap. The dependency injection page explains why constructor injection is the right default.
Validation and errors
Validation is where machine-coding rounds are often lost by stronger coders. They build the happy path beautifully, and then the interviewer types spend bob -5 equal asha and gets a stack trace.
Where validation goes
| Layer | Validates | Example |
|---|---|---|
| Driver | Syntax: right number of tokens, numbers that parse | "usage: settle <from> <to> <amount>" |
| Service | Business rules that need state | "unknown user zed", "bob owes asha only 10.00" |
| Model / strategy | Invariants of the object itself | "percentages add up to 90, expected 100" |
Rules that need state, like "does this user exist?", belong in the service. Rules about a value's own shape, like "an amount has at most two decimal places", belong next to that value. Don't validate everything in the driver. If you do, the service trusts its input, and a test or a future REST endpoint can corrupt the state.
Two exception types are enough
Define a small set of domain exceptions, usually just these two:
ValidationException: the input is malformed or breaks a rule.NotFoundException: something referenced doesn't exist.
The driver catches both, prints error: <message> and carries on to the next command. Anything else, such as a NullPointerException, is a bug, and it should crash loudly during development so you find it.
Validate, then mutate
Every service method should finish all its checks before it changes any state. In the worked example below, addExpense checks the payer, the participants, the split mode and the strategy's own rules, and only then updates the balance sheet and saves the expense. If a check fails halfway through a mutation, you need rollback logic, and rollback logic written at minute 55 of a timed round will have bugs.
Money
Never use floating point for money. 0.1 + 0.2 != 0.3 in every mainstream language, and a reviewer who sees double amount in a payments problem will mark it down. Use integer cents (or paise) and parse decimal strings by hand, as the example does, or use a decimal type (BigDecimal, Python's Decimal). Then decide what happens to indivisible remainders. When ₹100.00 is split three ways, someone pays the extra paisa. Say who, and test it.
Writing tests quickly
You won't have time for a full test suite. You do have time for five to eight tests that pin down the rules most likely to be wrong. Choose them like this:
- The arithmetic edge case. For splitting: the remainder cent. For parking: the partial hour. For booking: the boundary minute.
- One test per validation rule that protects money or state. For example, "percentages must total 100" and "can't settle more than is owed".
- "A rejected command changes nothing." This catches validate-after-mutate bugs.
- One end-to-end test through the driver. It catches parsing mistakes.
Test framework setup can eat ten minutes in an unfamiliar online IDE. If JUnit or pytest isn't already configured, a tiny check(condition, name) helper in a separate main is perfectly acceptable. Say so: "I'd normally use JUnit, but the environment doesn't have it set up, so these are plain assertions."
Worked example: an expense-sharing ledger
The problem, as an interviewer might state it
Friends on a trip want to track shared spending. Build a command-line ledger that supports:
user <id> <name>: register a person.spend <payer> <amount> <mode> <participants>: the payer paidamountfor the listed participants. The payer may or may not be one of them. Modes:
equal: participants area,b,c, and the amount is split equally.exact: participants area:12.50,b:7.50, and the shares must add up to the amount.percent: participants area:50,b:30,c:20, and the percentages must add up to 100.settle <from> <to> <amount>:frompaystoback, which can't exceed whatfromowes.balances [user]: list who owes whom, for everyone or one user.Amounts have at most two decimal places. Debts between two people should be netted: if A owes B 10 and B owes A 4, show only "A owes B 6". Invalid commands print an error and the program continues.
Clarifications and assumptions
These go in a comment at the top of the driver, written in the first eight minutes:
- Amounts are positive decimals with up to two places, stored as integer cents.
- Indivisible remainders go one cent each to the first participants listed, so
100.00 / 3is33.34, 33.33, 33.33. - Percentages are whole numbers. Fractional percentages are out of scope.
balancesoutput is sorted by debtor, then creditor, so it's deterministic and testable.- Single-threaded CLI, but the service methods are synchronized, so it's safe if the interviewer asks for concurrency.
Design
classDiagram
class ExpenseService {
-users: UserRepository
-expenses: ExpenseRepository
-balances: BalanceSheet
-strategies: map of name to SplitStrategy
+addUser(id, name) User
+addExpense(payer, totalCents, mode, participants, values) Expense
+settle(from, to, cents)
+balances(userOrNull) list of lines
}
class SplitStrategy {
<<interface>>
+split(totalCents, users, values) map of user to cents
}
class EqualSplit
class ExactSplit
class PercentSplit
class BalanceSheet {
-owed: debtor to creditor to cents
+add(debtor, creditor, cents)
+owed(debtor, creditor) long
+lines(userOrNull) list of lines
}
class UserRepository {
<<interface>>
+save(user)
+find(id) User
}
class ExpenseRepository {
<<interface>>
+save(payer, total, shares) Expense
+all() list of Expense
}
class CommandRunner {
+run(line) String
}
SplitStrategy <|.. EqualSplit
SplitStrategy <|.. ExactSplit
SplitStrategy <|.. PercentSplit
ExpenseService --> SplitStrategy
ExpenseService --> BalanceSheet
ExpenseService --> UserRepository
ExpenseService --> ExpenseRepository
CommandRunner --> ExpenseService
The design has three pieces worth explaining in the review.
Strategy for splitting. Each mode turns (total, participants, values) into a map of shares. Equal and percent are both "proportional to weights" (all weights 1, or the percentages), so they share one helper that does floor division and then hands out the leftover cents. Exact just checks that the sum matches. Adding a "shares" mode (a:2,b:1 meaning two-thirds and one-third) is a new four-line class, and that's exactly the extension interviewers like to ask for. The pattern is covered in behavioral patterns.
A netted balance sheet. It stores how much each debtor owes each creditor, keeping at most one direction non-zero for any pair. Recording "A owes B x" first combines it with any existing debt in either direction and then stores the net. That one method handles expenses and settlements. A settlement is just "the creditor now owes the debtor x", which cancels against the existing debt.
The driver owns syntax, the service owns rules. CommandRunner splits tokens, parses a:12.50 into a user and a cent value, and catches the two domain exceptions. The service never sees a raw string amount.
sequenceDiagram
participant CLI as CommandRunner
participant S as ExpenseService
participant U as UserRepository
participant P as SplitStrategy
participant B as BalanceSheet
participant E as ExpenseRepository
CLI->>S: addExpense(asha, 9000, equal, [asha, bob, chen], [])
S->>U: find payer and each participant
S->>P: split(9000, users, values)
P-->>S: asha 3000, bob 3000, chen 3000
Note over S: all checks passed, now mutate
S->>B: add(bob, asha, 3000)
S->>B: add(chen, asha, 3000)
S->>E: save(asha, 9000, shares)
S-->>CLI: Expense
The code
Each version is complete. It runs a built-in sample script by default, or a file of commands if you pass a path. The Java version has a separate test class, the Python version a unittest module, and the TypeScript version a node:test file.
// ExpenseApp.java (in a real round, split along the section comments)
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.regex.Pattern;
// ---- error/ValidationException.java, error/NotFoundException.java ----
class ValidationException extends RuntimeException {
ValidationException(String message) { super(message); }
}
class NotFoundException extends RuntimeException {
NotFoundException(String message) { super(message); }
}
// ---- model/Money.java ----
final class Money {
private static final Pattern AMOUNT = Pattern.compile("\\d{1,9}(\\.\\d{1,2})?");
private Money() {}
static long parseCents(String text) {
if (!AMOUNT.matcher(text).matches()) throw new ValidationException("invalid amount '" + text + "'");
String[] parts = text.split("\\.");
long cents = Long.parseLong(parts[0]) * 100;
if (parts.length == 2) cents += Long.parseLong((parts[1] + "0").substring(0, 2));
return cents;
}
static String format(long cents) { return String.format("%d.%02d", cents / 100, cents % 100); }
}
// ---- model/User.java, model/Expense.java ----
record User(String id, String name) {}
record Expense(long id, String payerId, long totalCents, Map<String, Long> shares) {}
// ---- split/*.java ----
interface SplitStrategy {
Map<String, Long> split(long totalCents, List<String> userIds, List<Long> values);
}
final class Splits {
private Splits() {}
/** Shares proportional to weights. Leftover cents go one each to the first users. */
static Map<String, Long> proportional(long total, List<String> users, List<Long> weights) {
long weightSum = weights.stream().mapToLong(Long::longValue).sum();
Map<String, Long> shares = new LinkedHashMap<>();
long assigned = 0;
for (int i = 0; i < users.size(); i++) {
long share = total * weights.get(i) / weightSum;
shares.put(users.get(i), share);
assigned += share;
}
Iterator<String> next = users.iterator();
for (long left = total - assigned; left > 0; left--) shares.merge(next.next(), 1L, Long::sum);
return shares;
}
static long sum(List<Long> values) { return values.stream().mapToLong(Long::longValue).sum(); }
}
final class EqualSplit implements SplitStrategy {
public Map<String, Long> split(long total, List<String> users, List<Long> values) {
if (!values.isEmpty()) throw new ValidationException("equal split takes no amounts");
return Splits.proportional(total, users, Collections.nCopies(users.size(), 1L));
}
}
final class ExactSplit implements SplitStrategy {
public Map<String, Long> split(long total, List<String> users, List<Long> values) {
long sum = Splits.sum(values);
if (sum != total)
throw new ValidationException("exact shares add up to " + Money.format(sum) + ", expected " + Money.format(total));
Map<String, Long> shares = new LinkedHashMap<>();
for (int i = 0; i < users.size(); i++) shares.put(users.get(i), values.get(i));
return shares;
}
}
final class PercentSplit implements SplitStrategy {
public Map<String, Long> split(long total, List<String> users, List<Long> values) {
long sum = Splits.sum(values);
if (sum != 100) throw new ValidationException("percentages add up to " + sum + ", expected 100");
return Splits.proportional(total, users, values);
}
}
// ---- repo/*.java ----
interface UserRepository {
void save(User user);
Optional<User> find(String id);
}
interface ExpenseRepository {
Expense save(String payerId, long totalCents, Map<String, Long> shares);
List<Expense> all();
}
final class InMemoryUserRepository implements UserRepository {
private final Map<String, User> byId = new HashMap<>();
public void save(User user) { byId.put(user.id(), user); }
public Optional<User> find(String id) { return Optional.ofNullable(byId.get(id)); }
}
final class InMemoryExpenseRepository implements ExpenseRepository {
private final List<Expense> expenses = new ArrayList<>();
public Expense save(String payerId, long totalCents, Map<String, Long> shares) {
Expense e = new Expense(expenses.size() + 1, payerId, totalCents, Map.copyOf(shares));
expenses.add(e);
return e;
}
public List<Expense> all() { return List.copyOf(expenses); }
}
// ---- service/BalanceSheet.java ----
final class BalanceSheet {
// owed.get(a).get(b) = cents a owes b. For any pair, at most one direction is non-zero.
private final Map<String, Map<String, Long>> owed = new HashMap<>();
long owed(String debtor, String creditor) {
return owed.getOrDefault(debtor, Map.of()).getOrDefault(creditor, 0L);
}
void add(String debtor, String creditor, long cents) {
if (debtor.equals(creditor) || cents == 0) return;
long net = owed(debtor, creditor) + cents - owed(creditor, debtor);
put(debtor, creditor, Math.max(0, net));
put(creditor, debtor, Math.max(0, -net));
}
private void put(String debtor, String creditor, long cents) {
if (cents == 0) {
Map<String, Long> row = owed.get(debtor);
if (row != null) row.remove(creditor);
} else {
owed.computeIfAbsent(debtor, k -> new HashMap<>()).put(creditor, cents);
}
}
List<String> lines(String userOrNull) {
List<String> out = new ArrayList<>();
new TreeMap<>(owed).forEach((debtor, row) -> new TreeMap<>(row).forEach((creditor, cents) -> {
if (userOrNull == null || userOrNull.equals(debtor) || userOrNull.equals(creditor))
out.add(debtor + " owes " + creditor + " " + Money.format(cents));
}));
return out;
}
}
// ---- service/ExpenseService.java ----
final class ExpenseService {
private static final Pattern USER_ID = Pattern.compile("[a-z0-9_]{1,20}");
private final UserRepository users;
private final ExpenseRepository expenses;
private final Map<String, SplitStrategy> strategies;
private final BalanceSheet balances = new BalanceSheet();
ExpenseService(UserRepository users, ExpenseRepository expenses, Map<String, SplitStrategy> strategies) {
this.users = users; this.expenses = expenses; this.strategies = strategies;
}
synchronized User addUser(String id, String name) {
if (!USER_ID.matcher(id).matches())
throw new ValidationException("user id must be 1-20 of a-z, 0-9 or _");
if (users.find(id).isPresent()) throw new ValidationException("user " + id + " already exists");
User user = new User(id, name);
users.save(user);
return user;
}
synchronized Expense addExpense(String payerId, long totalCents, String mode,
List<String> participants, List<Long> values) {
requireUser(payerId);
if (totalCents <= 0) throw new ValidationException("amount must be positive");
if (participants.isEmpty()) throw new ValidationException("at least one participant is required");
if (new HashSet<>(participants).size() != participants.size())
throw new ValidationException("a participant is listed twice");
participants.forEach(this::requireUser);
SplitStrategy strategy = strategies.get(mode);
if (strategy == null)
throw new ValidationException("unknown split '" + mode + "', expected one of " + strategies.keySet());
if (!values.isEmpty() && values.size() != participants.size())
throw new ValidationException("every participant needs a value");
Map<String, Long> shares = strategy.split(totalCents, participants, values);
// all checks passed: now mutate
shares.forEach((user, share) -> balances.add(user, payerId, share));
return expenses.save(payerId, totalCents, shares);
}
synchronized void settle(String from, String to, long cents) {
requireUser(from);
requireUser(to);
if (cents <= 0) throw new ValidationException("amount must be positive");
long owed = balances.owed(from, to);
if (cents > owed)
throw new ValidationException(from + " owes " + to + " only " + Money.format(owed));
balances.add(to, from, cents); // a payment back cancels against the debt
}
synchronized List<String> balances(String userOrNull) {
if (userOrNull != null) requireUser(userOrNull);
return balances.lines(userOrNull);
}
private void requireUser(String id) {
if (users.find(id).isEmpty()) throw new NotFoundException("unknown user " + id);
}
}
// ---- cli/CommandRunner.java ----
final class CommandRunner {
private final ExpenseService service;
CommandRunner(ExpenseService service) { this.service = service; }
String run(String line) {
String[] t = line.trim().split("\\s+");
try {
switch (t[0]) {
case "user": {
need(t.length >= 3, "user <id> <name>");
service.addUser(t[1], String.join(" ", Arrays.copyOfRange(t, 2, t.length)));
return "added " + t[1];
}
case "spend": {
need(t.length == 5, "spend <payer> <amount> <equal|exact|percent> <participants>");
List<String> users = new ArrayList<>();
List<Long> values = new ArrayList<>();
for (String part : t[4].split(",")) {
String[] kv = part.split(":", 2);
users.add(kv[0]);
if (kv.length == 2) values.add(t[3].equals("percent") ? parsePercent(kv[1]) : Money.parseCents(kv[1]));
}
Expense e = service.addExpense(t[1], Money.parseCents(t[2]), t[3], users, values);
return "expense #" + e.id() + " recorded";
}
case "settle": {
need(t.length == 4, "settle <from> <to> <amount>");
service.settle(t[1], t[2], Money.parseCents(t[3]));
return t[1] + " paid " + t[2] + " " + t[3];
}
case "balances": {
List<String> lines = service.balances(t.length > 1 ? t[1] : null);
return lines.isEmpty() ? "no balances" : String.join("\n", lines);
}
default:
throw new ValidationException("unknown command '" + t[0] + "'");
}
} catch (ValidationException | NotFoundException e) {
return "error: " + e.getMessage();
}
}
private static void need(boolean ok, String usage) {
if (!ok) throw new ValidationException("usage: " + usage);
}
private static long parsePercent(String text) {
if (!text.matches("\\d{1,3}")) throw new ValidationException("invalid percentage '" + text + "'");
return Long.parseLong(text);
}
}
// ---- Main.java ----
public class ExpenseApp {
static final String SAMPLE = """
user asha Asha Rao
user bob Bob Lee
user chen Chen Wu
spend asha 90.00 equal asha,bob,chen
spend bob 50 exact asha:20,chen:30
spend chen 100.01 percent asha:50,bob:25,chen:25
balances
settle bob asha 15
settle bob asha 10
spend dan 10 equal asha
spend asha 10 exact bob:3,chen:3
balances chen
""";
static ExpenseService newService() {
Map<String, SplitStrategy> strategies = new LinkedHashMap<>();
strategies.put("equal", new EqualSplit());
strategies.put("exact", new ExactSplit());
strategies.put("percent", new PercentSplit());
return new ExpenseService(new InMemoryUserRepository(), new InMemoryExpenseRepository(), strategies);
}
public static void main(String[] args) throws Exception {
List<String> lines = args.length > 0 ? Files.readAllLines(Path.of(args[0])) : SAMPLE.lines().toList();
CommandRunner cli = new CommandRunner(newService());
for (String line : lines) {
if (line.isBlank()) continue;
System.out.println("> " + line.trim());
System.out.println(cli.run(line));
}
}
}
"""expense_app.py: group expense ledger (in a real round, split along the section comments)."""
from __future__ import annotations
import re
import sys
import threading
from dataclasses import dataclass
from typing import Protocol
# ---- errors.py ----
class ValidationError(Exception):
"""Malformed input or a broken rule. The command is rejected and nothing changes."""
class NotFoundError(Exception):
"""A referenced user does not exist."""
# ---- model.py ----
_AMOUNT = re.compile(r"\d{1,9}(\.\d{1,2})?")
def parse_cents(text: str) -> int:
if not _AMOUNT.fullmatch(text):
raise ValidationError(f"invalid amount '{text}'")
whole, _, frac = text.partition(".")
return int(whole) * 100 + int((frac + "00")[:2])
def format_cents(cents: int) -> str:
return f"{cents // 100}.{cents % 100:02d}"
@dataclass(frozen=True)
class User:
id: str
name: str
@dataclass(frozen=True)
class Expense:
id: int
payer_id: str
total_cents: int
shares: dict[str, int]
# ---- split.py ----
class SplitStrategy(Protocol):
def split(self, total: int, users: list[str], values: list[int]) -> dict[str, int]: ...
def proportional(total: int, users: list[str], weights: list[int]) -> dict[str, int]:
"""Shares proportional to weights. Leftover cents go one each to the first users."""
weight_sum = sum(weights)
shares = {u: total * w // weight_sum for u, w in zip(users, weights)}
for u in users[: total - sum(shares.values())]:
shares[u] += 1
return shares
class EqualSplit:
def split(self, total: int, users: list[str], values: list[int]) -> dict[str, int]:
if values:
raise ValidationError("equal split takes no amounts")
return proportional(total, users, [1] * len(users))
class ExactSplit:
def split(self, total: int, users: list[str], values: list[int]) -> dict[str, int]:
if sum(values) != total:
raise ValidationError(
f"exact shares add up to {format_cents(sum(values))}, expected {format_cents(total)}")
return dict(zip(users, values))
class PercentSplit:
def split(self, total: int, users: list[str], values: list[int]) -> dict[str, int]:
if sum(values) != 100:
raise ValidationError(f"percentages add up to {sum(values)}, expected 100")
return proportional(total, users, values)
# ---- repo.py ----
class InMemoryUserRepository:
def __init__(self) -> None:
self._by_id: dict[str, User] = {}
def save(self, user: User) -> None:
self._by_id[user.id] = user
def find(self, user_id: str) -> User | None:
return self._by_id.get(user_id)
class InMemoryExpenseRepository:
def __init__(self) -> None:
self._expenses: list[Expense] = []
def save(self, payer_id: str, total: int, shares: dict[str, int]) -> Expense:
expense = Expense(len(self._expenses) + 1, payer_id, total, dict(shares))
self._expenses.append(expense)
return expense
def all(self) -> list[Expense]:
return list(self._expenses)
# ---- service.py ----
class BalanceSheet:
"""(debtor, creditor) -> cents. For any pair, at most one direction is stored."""
def __init__(self) -> None:
self._owed: dict[tuple[str, str], int] = {}
def owed(self, debtor: str, creditor: str) -> int:
return self._owed.get((debtor, creditor), 0)
def add(self, debtor: str, creditor: str, cents: int) -> None:
if debtor == creditor or cents == 0:
return
net = self.owed(debtor, creditor) + cents - self.owed(creditor, debtor)
self._put(debtor, creditor, max(0, net))
self._put(creditor, debtor, max(0, -net))
def _put(self, debtor: str, creditor: str, cents: int) -> None:
if cents:
self._owed[(debtor, creditor)] = cents
else:
self._owed.pop((debtor, creditor), None)
def lines(self, user: str | None = None) -> list[str]:
return [f"{d} owes {c} {format_cents(v)}"
for (d, c), v in sorted(self._owed.items()) if user in (None, d, c)]
_USER_ID = re.compile(r"[a-z0-9_]{1,20}")
class ExpenseService:
def __init__(self, users: InMemoryUserRepository, expenses: InMemoryExpenseRepository,
strategies: dict[str, SplitStrategy]) -> None:
self._users = users
self._expenses = expenses
self._strategies = strategies
self._balances = BalanceSheet()
self._lock = threading.Lock()
def add_user(self, user_id: str, name: str) -> User:
with self._lock:
if not _USER_ID.fullmatch(user_id):
raise ValidationError("user id must be 1-20 of a-z, 0-9 or _")
if self._users.find(user_id):
raise ValidationError(f"user {user_id} already exists")
user = User(user_id, name)
self._users.save(user)
return user
def add_expense(self, payer: str, total: int, mode: str,
participants: list[str], values: list[int]) -> Expense:
with self._lock:
self._require_user(payer)
if total <= 0:
raise ValidationError("amount must be positive")
if not participants:
raise ValidationError("at least one participant is required")
if len(set(participants)) != len(participants):
raise ValidationError("a participant is listed twice")
for p in participants:
self._require_user(p)
strategy = self._strategies.get(mode)
if strategy is None:
raise ValidationError(f"unknown split '{mode}', expected one of {list(self._strategies)}")
if values and len(values) != len(participants):
raise ValidationError("every participant needs a value")
shares = strategy.split(total, participants, values)
# all checks passed: now mutate
for user, share in shares.items():
self._balances.add(user, payer, share)
return self._expenses.save(payer, total, shares)
def settle(self, frm: str, to: str, cents: int) -> None:
with self._lock:
self._require_user(frm)
self._require_user(to)
if cents <= 0:
raise ValidationError("amount must be positive")
owed = self._balances.owed(frm, to)
if cents > owed:
raise ValidationError(f"{frm} owes {to} only {format_cents(owed)}")
self._balances.add(to, frm, cents) # a payment back cancels against the debt
def balances(self, user: str | None = None) -> list[str]:
with self._lock:
if user is not None:
self._require_user(user)
return self._balances.lines(user)
def _require_user(self, user_id: str) -> None:
if self._users.find(user_id) is None:
raise NotFoundError(f"unknown user {user_id}")
# ---- cli.py ----
class CommandRunner:
def __init__(self, service: ExpenseService) -> None:
self._service = service
def run(self, line: str) -> str:
t = line.split()
try:
if not t:
raise ValidationError("empty command")
if t[0] == "user":
self._need(len(t) >= 3, "user <id> <name>")
self._service.add_user(t[1], " ".join(t[2:]))
return f"added {t[1]}"
if t[0] == "spend":
self._need(len(t) == 5, "spend <payer> <amount> <equal|exact|percent> <participants>")
users, values = [], []
for part in t[4].split(","):
user, sep, raw = part.partition(":")
users.append(user)
if sep:
values.append(self._percent(raw) if t[3] == "percent" else parse_cents(raw))
expense = self._service.add_expense(t[1], parse_cents(t[2]), t[3], users, values)
return f"expense #{expense.id} recorded"
if t[0] == "settle":
self._need(len(t) == 4, "settle <from> <to> <amount>")
self._service.settle(t[1], t[2], parse_cents(t[3]))
return f"{t[1]} paid {t[2]} {t[3]}"
if t[0] == "balances":
lines = self._service.balances(t[1] if len(t) > 1 else None)
return "\n".join(lines) if lines else "no balances"
raise ValidationError(f"unknown command '{t[0]}'")
except (ValidationError, NotFoundError) as e:
return f"error: {e}"
@staticmethod
def _need(ok: bool, usage: str) -> None:
if not ok:
raise ValidationError(f"usage: {usage}")
@staticmethod
def _percent(text: str) -> int:
if not re.fullmatch(r"\d{1,3}", text):
raise ValidationError(f"invalid percentage '{text}'")
return int(text)
# ---- main.py ----
SAMPLE = """
user asha Asha Rao
user bob Bob Lee
user chen Chen Wu
spend asha 90.00 equal asha,bob,chen
spend bob 50 exact asha:20,chen:30
spend chen 100.01 percent asha:50,bob:25,chen:25
balances
settle bob asha 15
settle bob asha 10
spend dan 10 equal asha
spend asha 10 exact bob:3,chen:3
balances chen
"""
def new_service() -> ExpenseService:
strategies: dict[str, SplitStrategy] = {
"equal": EqualSplit(), "exact": ExactSplit(), "percent": PercentSplit()}
return ExpenseService(InMemoryUserRepository(), InMemoryExpenseRepository(), strategies)
def main(argv: list[str]) -> None:
if len(argv) > 1:
with open(argv[1], encoding="utf-8") as f:
lines = f.read().splitlines()
else:
lines = SAMPLE.splitlines()
cli = CommandRunner(new_service())
for line in lines:
if line.strip():
print(f"> {line.strip()}")
print(cli.run(line))
if __name__ == "__main__":
main(sys.argv)
// expense-app.ts (in a real round, split along the section comments)
import { readFileSync } from "node:fs";
// ---- errors.ts ----
export class ValidationError extends Error {}
export class NotFoundError extends Error {}
// ---- model.ts ----
const AMOUNT = /^\d{1,9}(\.\d{1,2})?$/;
export function parseCents(text: string): number {
if (!AMOUNT.test(text)) throw new ValidationError(`invalid amount '${text}'`);
const [whole, frac = ""] = text.split(".");
return Number(whole) * 100 + Number((frac + "00").slice(0, 2));
}
export const formatCents = (cents: number): string =>
`${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
export interface User { readonly id: string; readonly name: string }
export interface Expense {
readonly id: number;
readonly payerId: string;
readonly totalCents: number;
readonly shares: ReadonlyMap<string, number>;
}
// ---- split.ts ----
export interface SplitStrategy {
split(total: number, users: string[], values: number[]): Map<string, number>;
}
/** Shares proportional to weights. Leftover cents go one each to the first users. */
function proportional(total: number, users: string[], weights: number[]): Map<string, number> {
const weightSum = weights.reduce((a, b) => a + b, 0);
const shares = new Map(users.map((u, i) => [u, Math.floor((total * weights[i]) / weightSum)] as const));
let left = total - [...shares.values()].reduce((a, b) => a + b, 0);
for (const u of users) {
if (left-- <= 0) break;
shares.set(u, shares.get(u)! + 1);
}
return shares;
}
const sum = (xs: number[]): number => xs.reduce((a, b) => a + b, 0);
export class EqualSplit implements SplitStrategy {
split(total: number, users: string[], values: number[]): Map<string, number> {
if (values.length > 0) throw new ValidationError("equal split takes no amounts");
return proportional(total, users, users.map(() => 1));
}
}
export class ExactSplit implements SplitStrategy {
split(total: number, users: string[], values: number[]): Map<string, number> {
if (sum(values) !== total) {
throw new ValidationError(`exact shares add up to ${formatCents(sum(values))}, expected ${formatCents(total)}`);
}
return new Map(users.map((u, i) => [u, values[i]] as const));
}
}
export class PercentSplit implements SplitStrategy {
split(total: number, users: string[], values: number[]): Map<string, number> {
if (sum(values) !== 100) throw new ValidationError(`percentages add up to ${sum(values)}, expected 100`);
return proportional(total, users, values);
}
}
// ---- repo.ts ----
export interface UserRepository {
save(user: User): void;
find(id: string): User | undefined;
}
export interface ExpenseRepository {
save(payerId: string, totalCents: number, shares: Map<string, number>): Expense;
all(): readonly Expense[];
}
export class InMemoryUserRepository implements UserRepository {
private readonly byId = new Map<string, User>();
save(user: User): void { this.byId.set(user.id, user); }
find(id: string): User | undefined { return this.byId.get(id); }
}
export class InMemoryExpenseRepository implements ExpenseRepository {
private readonly expenses: Expense[] = [];
save(payerId: string, totalCents: number, shares: Map<string, number>): Expense {
const e: Expense = { id: this.expenses.length + 1, payerId, totalCents, shares: new Map(shares) };
this.expenses.push(e);
return e;
}
all(): readonly Expense[] { return [...this.expenses]; }
}
// ---- service.ts ----
export class BalanceSheet {
// owed.get(a).get(b) = cents a owes b. For any pair, at most one direction is non-zero.
private readonly owedMap = new Map<string, Map<string, number>>();
owed(debtor: string, creditor: string): number {
return this.owedMap.get(debtor)?.get(creditor) ?? 0;
}
add(debtor: string, creditor: string, cents: number): void {
if (debtor === creditor || cents === 0) return;
const net = this.owed(debtor, creditor) + cents - this.owed(creditor, debtor);
this.put(debtor, creditor, Math.max(0, net));
this.put(creditor, debtor, Math.max(0, -net));
}
private put(debtor: string, creditor: string, cents: number): void {
if (cents === 0) { this.owedMap.get(debtor)?.delete(creditor); return; }
if (!this.owedMap.has(debtor)) this.owedMap.set(debtor, new Map());
this.owedMap.get(debtor)!.set(creditor, cents);
}
lines(user?: string): string[] {
const out: string[] = [];
for (const debtor of [...this.owedMap.keys()].sort()) {
const row = this.owedMap.get(debtor)!;
for (const creditor of [...row.keys()].sort()) {
if (user === undefined || user === debtor || user === creditor) {
out.push(`${debtor} owes ${creditor} ${formatCents(row.get(creditor)!)}`);
}
}
}
return out;
}
}
const USER_ID = /^[a-z0-9_]{1,20}$/;
// Node runs this on one thread and no method awaits, so each call is atomic.
export class ExpenseService {
private readonly balanceSheet = new BalanceSheet();
constructor(
private readonly users: UserRepository,
private readonly expenses: ExpenseRepository,
private readonly strategies: Map<string, SplitStrategy>,
) {}
addUser(id: string, name: string): User {
if (!USER_ID.test(id)) throw new ValidationError("user id must be 1-20 of a-z, 0-9 or _");
if (this.users.find(id)) throw new ValidationError(`user ${id} already exists`);
const user = { id, name };
this.users.save(user);
return user;
}
addExpense(payerId: string, total: number, mode: string, participants: string[], values: number[]): Expense {
this.requireUser(payerId);
if (total <= 0) throw new ValidationError("amount must be positive");
if (participants.length === 0) throw new ValidationError("at least one participant is required");
if (new Set(participants).size !== participants.length) throw new ValidationError("a participant is listed twice");
participants.forEach((p) => this.requireUser(p));
const strategy = this.strategies.get(mode);
if (!strategy) {
throw new ValidationError(`unknown split '${mode}', expected one of ${[...this.strategies.keys()].join(", ")}`);
}
if (values.length > 0 && values.length !== participants.length) {
throw new ValidationError("every participant needs a value");
}
const shares = strategy.split(total, participants, values);
// all checks passed: now mutate
shares.forEach((share, user) => this.balanceSheet.add(user, payerId, share));
return this.expenses.save(payerId, total, shares);
}
settle(from: string, to: string, cents: number): void {
this.requireUser(from);
this.requireUser(to);
if (cents <= 0) throw new ValidationError("amount must be positive");
const owed = this.balanceSheet.owed(from, to);
if (cents > owed) throw new ValidationError(`${from} owes ${to} only ${formatCents(owed)}`);
this.balanceSheet.add(to, from, cents); // a payment back cancels against the debt
}
balances(user?: string): string[] {
if (user !== undefined) this.requireUser(user);
return this.balanceSheet.lines(user);
}
private requireUser(id: string): void {
if (!this.users.find(id)) throw new NotFoundError(`unknown user ${id}`);
}
}
// ---- cli.ts ----
export class CommandRunner {
constructor(private readonly service: ExpenseService) {}
run(line: string): string {
const t = line.trim().split(/\s+/);
try {
switch (t[0]) {
case "user":
need(t.length >= 3, "user <id> <name>");
this.service.addUser(t[1], t.slice(2).join(" "));
return `added ${t[1]}`;
case "spend": {
need(t.length === 5, "spend <payer> <amount> <equal|exact|percent> <participants>");
const users: string[] = [];
const values: number[] = [];
for (const part of t[4].split(",")) {
const [user, raw] = part.split(":", 2);
users.push(user);
if (raw !== undefined) values.push(t[3] === "percent" ? parsePercent(raw) : parseCents(raw));
}
const e = this.service.addExpense(t[1], parseCents(t[2]), t[3], users, values);
return `expense #${e.id} recorded`;
}
case "settle":
need(t.length === 4, "settle <from> <to> <amount>");
this.service.settle(t[1], t[2], parseCents(t[3]));
return `${t[1]} paid ${t[2]} ${t[3]}`;
case "balances": {
const lines = this.service.balances(t[1]);
return lines.length > 0 ? lines.join("\n") : "no balances";
}
default:
throw new ValidationError(`unknown command '${t[0]}'`);
}
} catch (e) {
if (e instanceof ValidationError || e instanceof NotFoundError) return `error: ${e.message}`;
throw e;
}
}
}
function need(ok: boolean, usage: string): void {
if (!ok) throw new ValidationError(`usage: ${usage}`);
}
function parsePercent(text: string): number {
if (!/^\d{1,3}$/.test(text)) throw new ValidationError(`invalid percentage '${text}'`);
return Number(text);
}
// ---- main.ts ----
const SAMPLE = `
user asha Asha Rao
user bob Bob Lee
user chen Chen Wu
spend asha 90.00 equal asha,bob,chen
spend bob 50 exact asha:20,chen:30
spend chen 100.01 percent asha:50,bob:25,chen:25
balances
settle bob asha 15
settle bob asha 10
spend dan 10 equal asha
spend asha 10 exact bob:3,chen:3
balances chen
`;
export function newService(): ExpenseService {
const strategies = new Map<string, SplitStrategy>([
["equal", new EqualSplit()],
["exact", new ExactSplit()],
["percent", new PercentSplit()],
]);
return new ExpenseService(new InMemoryUserRepository(), new InMemoryExpenseRepository(), strategies);
}
export function main(args: string[]): void {
const text = args.length > 0 ? readFileSync(args[0], "utf8") : SAMPLE;
const cli = new CommandRunner(newService());
for (const line of text.split("\n")) {
if (line.trim() === "") continue;
console.log(`> ${line.trim()}`);
console.log(cli.run(line));
}
}
if (require.main === module) main(process.argv.slice(2));
Sample run
All three versions print the same output for the built-in sample:
> user asha Asha Rao
added asha
> user bob Bob Lee
added bob
> user chen Chen Wu
added chen
> spend asha 90.00 equal asha,bob,chen
expense #1 recorded
> spend bob 50 exact asha:20,chen:30
expense #2 recorded
> spend chen 100.01 percent asha:50,bob:25,chen:25
expense #3 recorded
> balances
asha owes chen 20.01
bob owes asha 10.00
chen owes bob 5.00
> settle bob asha 15
error: bob owes asha only 10.00
> settle bob asha 10
bob paid asha 10
> spend dan 10 equal asha
error: unknown user dan
> spend asha 10 exact bob:3,chen:3
error: exact shares add up to 6.00, expected 10.00
> balances chen
asha owes chen 20.01
chen owes bob 5.00
Walk the reviewer through the third expense, because it shows the remainder rule. 100.01 at 50/25/25 percent is 5000.5, 2500.25 and 2500.25 cents. Floor division gives 5000, 2500 and 2500, which leaves one cent over, and that cent goes to asha, the first participant. Combined with the earlier expenses, the netting produces the three lines under balances.
The tests
Ten checks in Java and five test cases in Python and TypeScript, covering the rules most likely to break: the remainder, both "must add up" rules, netting in both directions, overpaying, "a rejected command changes nothing", and the driver's error reporting.
// ExpenseTests.java: plain checks, no framework needed. Compile with ExpenseApp.java.
import java.util.*;
public class ExpenseTests {
private static int passed = 0;
static void check(boolean ok, String name) {
if (!ok) throw new AssertionError("FAILED: " + name);
passed++;
}
static void expectError(Runnable action, String fragment, String name) {
try {
action.run();
} catch (ValidationException | NotFoundException e) {
check(e.getMessage().contains(fragment), name + " (got: " + e.getMessage() + ")");
return;
}
check(false, name + " (no error thrown)");
}
static ExpenseService serviceWith(String... ids) {
ExpenseService s = ExpenseApp.newService();
for (String id : ids) s.addUser(id, id);
return s;
}
public static void main(String[] args) {
Map<String, Long> shares = new EqualSplit().split(100, List.of("a", "b", "c"), List.of());
check(shares.equals(Map.of("a", 34L, "b", 33L, "c", 33L)), "leftover cent goes to the first participant");
expectError(() -> new PercentSplit().split(100, List.of("a", "b"), List.of(60L, 30L)),
"add up to 90", "percentages must total 100");
ExpenseService s = serviceWith("a", "b");
s.addExpense("a", 1000, "equal", List.of("a", "b"), List.of());
s.addExpense("b", 400, "exact", List.of("a"), List.of(400L));
check(s.balances(null).equals(List.of("b owes a 1.00")), "debts net across directions");
expectError(() -> s.settle("b", "a", 101), "only 1.00", "cannot settle more than owed");
check(s.balances(null).equals(List.of("b owes a 1.00")), "failed settle changes nothing");
s.settle("b", "a", 100);
check(s.balances(null).isEmpty(), "settling in full clears the debt");
expectError(() -> s.addExpense("a", 500, "equal", List.of("a", "zed"), List.of()),
"unknown user zed", "unknown participant rejected");
check(s.balances(null).isEmpty(), "rejected expense changes nothing");
CommandRunner cli = new CommandRunner(serviceWith("a"));
check(cli.run("spend a 1.234 equal a").startsWith("error: invalid amount"), "driver reports a bad amount");
check(cli.run("frobnicate").startsWith("error: unknown command"), "driver reports an unknown command");
System.out.println(passed + " checks passed");
}
}
# test_expense_app.py: run with python -m unittest test_expense_app
import unittest
from expense_app import (CommandRunner, EqualSplit, NotFoundError, PercentSplit,
ValidationError, new_service)
def service_with(*ids: str):
s = new_service()
for i in ids:
s.add_user(i, i)
return s
class LedgerTests(unittest.TestCase):
def test_leftover_cent_goes_to_first_participant(self):
self.assertEqual(EqualSplit().split(100, ["a", "b", "c"], []), {"a": 34, "b": 33, "c": 33})
def test_percentages_must_total_100(self):
with self.assertRaisesRegex(ValidationError, "add up to 90"):
PercentSplit().split(100, ["a", "b"], [60, 30])
def test_debts_net_and_settle(self):
s = service_with("a", "b")
s.add_expense("a", 1000, "equal", ["a", "b"], [])
s.add_expense("b", 400, "exact", ["a"], [400])
self.assertEqual(s.balances(), ["b owes a 1.00"])
with self.assertRaisesRegex(ValidationError, "only 1.00"):
s.settle("b", "a", 101)
self.assertEqual(s.balances(), ["b owes a 1.00"]) # failed settle changed nothing
s.settle("b", "a", 100)
self.assertEqual(s.balances(), [])
def test_rejected_expense_changes_nothing(self):
s = service_with("a")
with self.assertRaisesRegex(NotFoundError, "unknown user zed"):
s.add_expense("a", 500, "equal", ["a", "zed"], [])
self.assertEqual(s.balances(), [])
def test_driver_reports_errors_and_continues(self):
cli = CommandRunner(service_with("a"))
self.assertTrue(cli.run("spend a 1.234 equal a").startswith("error: invalid amount"))
self.assertTrue(cli.run("frobnicate").startswith("error: unknown command"))
self.assertEqual(cli.run("balances"), "no balances")
if __name__ == "__main__":
unittest.main()
// expense-app.test.ts: run with npx tsx --test expense-app.test.ts
import { test } from "node:test";
import assert from "node:assert/strict";
import { CommandRunner, EqualSplit, NotFoundError, PercentSplit, ValidationError, newService } from "./expense-app";
function serviceWith(...ids: string[]) {
const s = newService();
ids.forEach((id) => s.addUser(id, id));
return s;
}
test("leftover cent goes to the first participant", () => {
const shares = new EqualSplit().split(100, ["a", "b", "c"], []);
assert.deepEqual([...shares], [["a", 34], ["b", 33], ["c", 33]]);
});
test("percentages must total 100", () => {
assert.throws(() => new PercentSplit().split(100, ["a", "b"], [60, 30]), ValidationError);
});
test("debts net across directions and settle", () => {
const s = serviceWith("a", "b");
s.addExpense("a", 1000, "equal", ["a", "b"], []);
s.addExpense("b", 400, "exact", ["a"], [400]);
assert.deepEqual(s.balances(), ["b owes a 1.00"]);
assert.throws(() => s.settle("b", "a", 101), /only 1\.00/);
assert.deepEqual(s.balances(), ["b owes a 1.00"]);
s.settle("b", "a", 100);
assert.deepEqual(s.balances(), []);
});
test("rejected expense changes nothing", () => {
const s = serviceWith("a");
assert.throws(() => s.addExpense("a", 500, "equal", ["a", "zed"], []), NotFoundError);
assert.deepEqual(s.balances(), []);
});
test("driver reports errors and continues", () => {
const cli = new CommandRunner(serviceWith("a"));
assert.match(cli.run("spend a 1.234 equal a"), /^error: invalid amount/);
assert.match(cli.run("frobnicate"), /^error: unknown command/);
assert.equal(cli.run("balances"), "no balances");
});
The live extension
Suppose the interviewer asks, with fifteen minutes left: "Add a shares mode, where a:2,b:1 means a pays two thirds."
"That's a new strategy. Shares are weights, so it reuses the proportional helper. I register it under
sharesinnewService. The service, the balance sheet and the driver don't change, apart from the driver parsing share values as integers like percentages."
final class ShareSplit implements SplitStrategy {
public Map<String, Long> split(long total, List<String> users, List<Long> values) {
if (values.size() != users.size() || values.stream().anyMatch(v -> v <= 0))
throw new ValidationException("every participant needs a positive share count");
return Splits.proportional(total, users, values);
}
}
// in newService(): strategies.put("shares", new ShareSplit());
// in CommandRunner: parse values as integers when the mode is "percent" or "shares"
That's two minutes of work, and it's the payoff for the 30 seconds it took to introduce SplitStrategy at minute 20.
Other extensions to be ready for, with the change each needs:
| Extension | Where the change goes |
|---|---|
| Show an expense history per user | A query method on ExpenseRepository, plus a history <user> command |
| Simplify debts (A owes B, B owes C, so A pays C) | A new simplify() on BalanceSheet: compute each person's net position, then greedily match the largest debtor with the largest creditor |
| Groups (trips) with separate ledgers | A Group holding its own BalanceSheet, and the service keyed by group id |
| Persist to a file | A file-backed repository behind the same interfaces, with the balance sheet rebuilt from expense history on load |
| Concurrent access | Already synchronized. For more throughput, lock per group, not per pair, because one expense touches many pairs |
What to say in the review
Prepare four or five sentences that summarise the design:
"The driver parses and formats, and the service enforces rules and is the only thing that mutates state. Splitting is a strategy, so new modes are new classes. Money is integer cents, with a documented remainder rule. The balance sheet keeps debts netted per pair, and settlements reuse the same netting. Every command validates fully before mutating, and the tests check that rejected commands change nothing. Known gaps: no debt simplification, no history command, and percentages must be whole numbers."
Common failure modes in machine coding
| Failure | Symptom | Fix |
|---|---|---|
| Big-bang build | Nothing runs until minute 70 | The feature loop: one command end to end, then run |
| Parsing tangled with logic | split(",") inside the service | Driver parses, service receives typed arguments |
| Crash on bad input | Stack trace in the demo | Two domain exceptions, caught in the driver |
| Floating-point money | 33.333333333333336 in the output | Integer cents or a decimal type |
| Framework detour | 15 minutes setting up a web server | Ask, then assume a CLI and in-memory storage |
| Global state | Static maps shared between tests | Construct the service in main and in each test |
| Unfinished optional feature | The extra feature breaks the build at minute 88 | Hard stop at 85, and never start something you can't finish |
| Silent assumptions | The reviewer disagrees with the rounding | Write assumptions at the top in the first eight minutes |
Many of these mistakes are explained in more depth, with before-and-after code, in Common LLD Mistakes.
The checklist
Run through this before you say "I'm done", or at minute 85 at the latest.
It runs
- It compiles from a clean state with no warnings you can't explain.
- The sample input produces the expected output.
-
Bad input prints
error: ...and the program keeps going.
Structure
- Models, repositories, services and the driver are in separate files or clearly marked sections.
- The service receives typed arguments, never raw command strings.
- Dependencies are passed through constructors, with no static mutable state.
- Interfaces exist where extension is expected (strategies, repositories), and nowhere else.
Correctness
- Money uses integer minor units or a decimal type.
- Every mutating method validates fully before changing state.
- Rounding and remainder rules are explicit and tested.
- Output ordering is deterministic.
Evidence
- Five to eight tests or checks cover the core rules and one end-to-end path.
- Assumptions and known gaps are written at the top of the driver or in a README.
- You can explain how to add the most likely extension in one sentence.
Interview questions
- "Why does the service take a map of strategies instead of a
switchon the mode?" New modes become new classes plus one registration line. The service doesn't change, and each strategy's rules can be tested alone. Aswitchwould grow with every mode and mix every mode's validation into one method. - "Why integer cents rather than
double?" Binary floating point can't represent most decimal fractions exactly, so sums drift and comparisons like "shares add up to the total" fail unpredictably. Integer cents are exact. The only remaining question is how to distribute remainders, and that becomes an explicit, tested rule. - "What happens if
addExpensefails halfway through?" It can't, by construction. All validation, including the strategy's own checks, happens before the first mutation. The test "rejected expense changes nothing" pins that behaviour down. - "How would you switch to a database?" Implement
UserRepositoryandExpenseRepositoryagainst the database. The balance sheet becomes either a table updated in the same transaction as the expense, or a projection rebuilt from expense history. The service code stays the same, apart from transaction boundaries. - "Is this thread-safe?" In Java and Python, yes, because every public service method takes the same lock, so each command is atomic. It's coarse: two unrelated groups would serialise. In TypeScript on Node, each method is synchronous and runs to completion, so there's no interleaving. If a method ever awaited I/O in the middle, it would need a per-group mutex or a queue.
- "Why is parsing in
CommandRunnerand not in the service?" The service's job is the rules. Keeping text out of it means tests call it with typed values, a REST layer could reuse it unchanged, and syntax errors and rule violations stay separate concerns. - "How would you implement debt simplification?" Compute each person's net balance (total owed to them minus total they owe). Repeatedly match the largest creditor with the largest debtor, record a transfer of the smaller amount, and reduce both. That produces at most n − 1 transfers. Finding the true minimum number of transfers is a much harder combinatorial problem, and this greedy approach is the usual interview answer.