2Brute2Best
🔥0
Brute2Best · Low-Level Design (C++23)

Naive code → what breaks → clean design.

Don't memorise 23 abstract definitions. Build three real systems sprint by sprint — a Food Delivery app, a Trading Engine and an RPG Game — and fix each pain point with the right pattern in Modern C++23.

01
Foundations
Classes, interfaces, ownership & UML (F1–F7)
02
Food Delivery
SOLID + Strategy, Observer, State, Factory, Adapter, Facade
03
Trading Engine
Builder, Singleton, Chain, Command, Mediator, Iterator
04
RPG Game
Decorator, Composite, Memento, Prototype, Flyweight, Visitor
05
19 Practice Problems
Unlocked as you finish the patterns they need

Part 1 · 7 pages

Foundations & Modern C++ Toolkit
0/7
F1
Classes & Encapsulation

class vs struct, private state, class invariants, and const correctness so objects can never enter an invalid state.

Encapsulation · Class Invariants
F2
Inheritance & Polymorphism

virtual methods, override, why a virtual destructor is mandatory on polymorphic bases, and vtable intuition.

Runtime Polymorphism · Virtual Dispatch
Needs F1
F3
Interfaces in C++

Pure virtual classes as contracts, decoupling callers from implementations, and swapping fakes in tests.

Program to an Interface
Needs F2
F4
Composition Over Inheritance

Why deep inheritance hierarchies explode when requirements cross-cut, and how assembling small pluggable parts keeps designs flexible.

Has-A vs Is-A · Delegation
Needs F3
F5
Ownership in Designs

Who owns what: unique_ptr for exclusive ownership, shared_ptr when lifetime is truly shared, and raw pointers/references as non-owning observers.

RAII · Ownership Semantics
Needs F4
F6
Reading Class Diagrams & Code Smells

Read and draw the 5 UML arrows (implements, inherits, composes, aggregates, depends) and map common code smells directly to SOLID principles.

UML · SOLID Map
Needs F5
F7
Modern C++ Toolkit for Design

enum class, concepts vs virtual interfaces, std::variant, std::expected, std::format/std::print, ranges, and std::span.

C++20/23 Idioms
Needs F6

Part 2 · Story A · 9 chapters

Story A — Food Delivery System
0/9
A1
Support UPI, Card & Wallet Payments

An if/else chain on payment type grows with every new method. Extract a PaymentStrategy interface so new gateways plug in without editing Checkout.

Strategy · Open-Closed Principle (OCP)
Needs F3, F5
A2
Splitting a God OrderService

OrderService validates, prices, charges, persists, and sends SMS in one method — every team's change touches the same file.

Single Responsibility Principle (SRP)
Needs A1
A3
Notify Customer, Restaurant & Rider on Events

OrderService hardcodes calls to each notifier. Turn order events into a publish-subscribe bus so listeners attach without touching order logic.

Observer
Needs A2
A4
Order Lifecycle & Cancel Rules

Placed → Accepted → Cooking → PickedUp → Delivered has different cancel and transition rules at every stage, causing status switches in every method.

State
Needs A3
A5
Creating Deliveries & Gateways Without Scattered new

Callers construct concrete gateways and delivery workflows directly with make_unique, duplicating creation rules across the codebase.

Factory Method · Simple Factory
Needs A1
A6
Swapping DB & Payment Gateway in Tests

High-level order logic instantiates SqlOrderRepository and RazorpayGateway directly, making unit tests hit the network and database.

Dependency Inversion Principle (DIP) · Constructor Injection
Needs A2, A5
A7
Cash-on-Delivery Refunds & Fat Partner Interfaces

CashOnDelivery throws 'not supported' inside refund(), and small cloud kitchens are forced to implement dine-in table booking methods.

Liskov Substitution Principle (LSP) · Interface Segregation Principle (ISP)
Needs A6
A8
Integrating a Partner Restaurant's Legacy API

A national pizza chain's SDK uses XML payloads and paise integers, which doesn't match our clean MenuProvider interface.

Adapter
Needs A6
A9
One-Call Checkout Across Five Subsystems

Mobile and web controllers both juggle cart, inventory, pricing, payment, rider dispatch, and notifications in 20 lines of fragile glue.

Facade
Needs A8

Part 3 · Story B · 9 chapters

Story B — Low-Latency Trading System
0/9
B1
Orders With Optional Limit, Stop, Validity & Iceberg Qty

An 8-argument Order constructor leads to swapped parameters and half-built invalid orders. Build validated orders step by step.

Builder
Needs F1, F7
B2
Shared Exchange Config & Why Singleton Hurts Tests

Everyone needs one ExchangeConfig and market-data session, but global state leaks between tests. Learn Meyer's Singleton and when DI is better.

Singleton
Needs A6
B3
Pre-Trade Risk Pipeline: KYC, Margin, Max Qty & Circuit Limits

A giant validateOrder() function mixes KYC, balance, lot-size, and price-band checks that vary by account tier.

Chain of Responsibility
Needs A1
B4
Place, Modify & Cancel With Audit Log and Undo

Direct method calls leave no audit trail and no way to roll back a batch of desk orders when a risk limit trips.

Command
Needs A3
B5
Supporting NSE and BSE Without Mixing Components

Each exchange has its own order router, fee calculator, and symbol mapper — accidentally pairing an NSE router with a BSE fee table corrupts trades.

Abstract Factory
Needs A5
B6
Matching Buyers and Sellers Through an Order Book

Traders and desk algorithms holding direct references to each other create a tangled mesh; centralize matching inside an OrderBook mediator.

Mediator
Needs A3
B7
Caching & Permission-Gating Paid Market Data

Every quote lookup hits a slow paid feed and basic users can query Level-2 depth they haven't subscribed to.

Proxy
Needs F3
B8
TWAP & VWAP Execution Algos Sharing a Skeleton

TWAP and VWAP copy-paste pre-check, child-order dispatch, and fill reporting, differing only in how they slice quantity.

Template Method
Needs A1
B9
Walking Price Levels Without Exposing Order-Book Internals

Callers reach into the order book's internal containers to scan top-N levels or filter institutional fills.

Iterator
Needs B6

Part 4 · Story C · 8 chapters

Story C — 2D RPG Game Engine
0/8
C1
Stackable Power-Ups: Shield, Speed & Double Damage

Creating ShieldHero, SpeedHero, and ShieldSpeedDoubleDamageHero causes a 2^N subclass explosion.

Decorator
Needs F4
C2
Bags Inside Pouches Inside the Inventory

Separate loops for single items vs bags break as soon as a player puts a potion pouch inside a backpack.

Composite
Needs F3
C3
Save Checkpoints & Restore Without Exposing Private State

The checkpoint manager reaches into Hero's private HP, mana, and cooldown fields, breaking encapsulation.

Memento
Needs F1, B4
C4
Spawning Waves of Enemies From Tuned Templates

Every goblin spawn re-parses loot tables, AI weights, and resistances from config instead of cloning a pre-tuned prototype.

Prototype
Needs A5
C5
10,000 Trees and Bullets Without Blowing Up RAM

Each tree instance duplicates a 4 MB mesh and texture array in memory instead of sharing intrinsic sprite data.

Flyweight
Needs F5
C6
Entities × Renderers (OpenGL, Vulkan, Headless)

Combining 5 entity types with 3 graphics APIs creates 15 subclasses; split the abstraction from the renderer implementation.

Bridge
Needs F4
C7
XP Calculation, JSON Export & Damage Reports Over Entities

Adding a new analytics report or save exporter forces edits to Hero, Monster, Trap, and Chest classes.

Visitor
Needs A4
C8
Spell & Cheat-Code Mini Expression Language

Ad-hoc string splitting for spell formulas like 'FIRE 20 + 2 * LEVEL' turns into an unmaintainable parser.

Interpreter
Needs C2

Part 5 · 19 interview problems

LLD Interview Practice (Easy → Hard)
0/19
P1Easy
Design a Pluggable Logger Framework

Log levels (DEBUG/INFO/WARN/ERROR), chained level filters, and pluggable sinks (console, file, memory ring-buffer).

Singleton · Chain of Responsibility · Strategy
Needs B2, B3
P2Easy
Design Tic-Tac-Toe (N×N, Human & Bot Strategies)

O(1) row/col/diagonal win tracking on an N×N board with pluggable move strategies and clean turn management.

Strategy · Single Responsibility Principle (SRP)
Needs A1, A2
P3Easy
Design Snake & Ladder

Configurable board entities (snakes, ladders, boost cells), pluggable dice (single, crooked, multi-dice), and multi-player turn loop.

Factory Method · Strategy
Needs A1, A5
P4Easy
Design a Vending Machine

Idle → HasMoney → Dispensing → OutOfStock state machine with coin/note inventory, refund on cancel, and change calculation.

State
Needs A4
P5Medium
Design a Multi-Floor Parking Lot

Spot types (Bike, Compact, Large), nearest vs lowest-floor spot allocation strategies, tickets, and hourly/flat fee strategies.

Strategy · Factory Method · Singleton
Needs A1, A5, B2
P6Medium
Design an Extensible Cache (LRU / LFU Eviction)

Separate storage from eviction policy so the cache supports O(1) LRU or LFU eviction behind a clean generic interface.

Strategy · Program to an Interface
Needs F3, A1
P7Medium
Design an In-Memory File System With Search & Size Visitors

Files and directories as a uniform tree, supporting mkdir, ls, disk-usage calculation, and predicate search filters.

Composite · Visitor
Needs C2, C7
P8Medium
Design a Library Management System

Book titles vs physical barcoded copies, reservations, overdue fine calculation, and hold-queue notifications when a copy returns.

Observer · Dependency Inversion Principle (DIP)
Needs A3, A6
P9Medium
Design an ATM & Cash Dispenser

Session state machine (CardInserted → Authenticated → Transacting) paired with a ₹2000 → ₹500 → ₹100 note-dispensing chain.

State · Chain of Responsibility
Needs A4, B3
P10Medium
Design a Multi-Channel Notification Service With Retries

Route events to Email/SMS/Push channels and wrap senders with retry, rate-limit, and metrics decorators.

Observer · Strategy · Decorator
Needs A3, C1
P11Medium
Design a Thread-Safe Rate Limiter (Token Bucket & Sliding Window)

Per-client rate limiting with swappable Token Bucket and Sliding Window Log algorithms under concurrent requests.

Strategy · Concurrency
Needs A1
P12Medium
Design Splitwise (Equal, Exact & Percent Splits + Simplify Debt)

Validate and split expenses across groups using Equal, Exact, and Percentage strategies, maintain net balances, and settle up.

Strategy · Factory Method
Needs A1, A5
P13Hard
Design a Multi-Car Elevator System

Elevator car states (Idle, MovingUp, MovingDown), hall/cabin button commands, and LOOK vs nearest-car dispatch strategies.

State · Strategy · Command
Needs A4, B4
P14Medium
Design a Shopping Cart Withstacked Coupons & Restock Alerts

Stack percentage, flat, and category-cap coupons as price decorators and notify back-in-stock subscribers when inventory replenishes.

Observer · Decorator · Strategy
Needs A3, C1
P15Medium
Design a Hotel Room Booking System

Date-range availability, reservation lifecycle (Tentative → Confirmed → CheckedIn → Cancelled), and seasonal/weekend pricing strategies.

Builder · State · Strategy
Needs B1, A4
P16Hard
Design BookMyShow With Concurrent Seat Locking

Cities, cinemas, shows, and atomic temporary seat holds with TTL expiry so two users can never double-book the same seat.

Facade · State · Concurrency
Needs A9, A4
P17Hard
Design an In-Memory Pub-Sub Message Queue With Offsets

Topics, append-only message logs, independent per-subscriber offsets, replay from offset, and worker consumption.

Observer · Mediator · Concurrency
Needs A3, B6
P18Hard
Design Uber / Ola Ride Dispatch & Trip Lifecycle

Driver matching (nearest vs highest-rated), surge pricing strategies, trip state machine, and live rider/driver status updates.

Strategy · State · Observer
Needs A1, A3, A4
P19Hard
Design Chess With Move Validation & Full Undo/Redo

Per-piece movement rules, board validation, algebraic move history, and reversible Command + Memento snapshots for undo/redo.

Factory Method · Strategy · Command · Memento
Needs A5, B4, C3
asked often in interviews· includes a Modern C++20/23 comparison