Episode 9 — System Design / 9.1 — LLD Foundations

9.1 LLD Foundations — Quick Revision

Compact cheat sheet. Print-friendly.

How to use this material (instructions)

  1. Skim top-to-bottom in one pass before quizzes or interviews.
  2. If a row feels fuzzy — reopen the matching lesson in README.md9.1.a...9.1.e.
  3. Drills9.1-Exercise-Questions.md.
  4. Polished phrasing9.1-Interview-Questions.md.

9.1.a What Is LLD

HLD vs LLD

┌─────────────┬──────────────────────────┬──────────────────────────┐
│             │ HLD                      │ LLD                      │
├─────────────┼──────────────────────────┼──────────────────────────┤
│ Scope       │ Entire system            │ Single service/module    │
│ Focus       │ Services, DBs, protocols │ Classes, methods, patterns│
│ Artifacts   │ Architecture diagrams    │ Class + sequence diagrams│
│ Audience    │ Architects, leads        │ Developers               │
│ Question    │ "Design Twitter arch"    │ "Design parking lot LLD" │
│ Abstraction │ Very high                │ Code-level               │
└─────────────┴──────────────────────────┴──────────────────────────┘

Components of Good LLD

ComponentPurpose
ClassesBlueprint for objects — attributes + methods
InterfacesContracts — define WHAT, not HOW
RelationshipsHow classes connect — association, composition, inheritance
MethodsBehavior — clear names, typed params, single purpose
Design PatternsProven solutions — Strategy, Factory, Observer, etc.

Key Principles

  • Separation of Concerns — one class = one responsibility
  • Open/Closed — extend via new classes, do not modify existing ones
  • Depend on Abstractions — code to interfaces, not concrete classes

9.1.b OOP Fundamentals

The Four Pillars

┌─────────────────┬──────────────────────────────────────────────┐
│ Pillar          │ One-liner                                    │
├─────────────────┼──────────────────────────────────────────────┤
│ Encapsulation   │ Bundle data + methods; restrict direct access│
│ Inheritance     │ Child reuses parent's code ("is-a")          │
│ Polymorphism    │ Same interface, different behavior at runtime│
│ Abstraction     │ Expose what matters, hide complexity         │
└─────────────────┴──────────────────────────────────────────────┘

Access Modifiers (TypeScript)

ModifierSymbol (UML)Access
public+Anyone
private-Only the class itself
protected#Class + subclasses
readonly(none)Set once in constructor

Polymorphism Types

Compile-time (Static)        Runtime (Dynamic)
─────────────────────        ─────────────────
Method Overloading           Method Overriding
Same name, diff params       Same name, diff class
Resolved at compile time     Resolved at runtime
TS overload signatures       extends + override method

Abstract Class vs Interface

┌──────────────────┬────────────────────┬────────────────────┐
│                  │ Abstract Class     │ Interface          │
├──────────────────┼────────────────────┼────────────────────┤
│ Implementation   │ Yes (concrete methods)│ No              │
│ State            │ Yes (properties)   │ No                 │
│ Constructor      │ Yes                │ No                 │
│ Multi-inherit    │ Single extends     │ Multiple implements│
│ Use when         │ Shared behavior +  │ Pure contract,     │
│                  │ enforced contract  │ multiple impls     │
└──────────────────┴────────────────────┴────────────────────┘

Golden Rule

Favor composition over inheritance. Use inheritance for clear, stable "is-a" relationships only. Use composition for "has-a" and when behavior needs flexibility.


9.1.c Class Relationships

Relationship Spectrum (weakest → strongest)

Dependency ┄┄► Association ── Aggregation ◇── Composition ◆──
 "uses"        "knows"        "has-a"         "owns-a"
 temporary     persistent     weak whole-part  strong, same lifetime

Quick Reference Table

┌───────────────┬────────┬──────────┬──────────────────────────────┐
│ Relationship  │ Symbol │ Lifecycle│ Example                      │
├───────────────┼────────┼──────────┼──────────────────────────────┤
│ Dependency    │ ┄┄┄►   │ None     │ Order uses Logger in method  │
│ Association   │ ─────  │ None     │ Teacher ↔ Student            │
│ Aggregation   │ ◇────  │ Weak     │ Department ◇── Employee      │
│ Composition   │ ◆────  │ Strong   │ House ◆── Room               │
│ Inheritance   │ ──▷    │ N/A      │ Dog ──▷ Animal               │
│ Implementation│ ┄┄▷    │ N/A      │ Circle ┄┄▷ Shape (interface) │
└───────────────┴────────┴──────────┴──────────────────────────────┘

Aggregation vs Composition Litmus Test

Question 1: Can the PART exist without the WHOLE?
  YES → Aggregation     (Employee without Department = still exists)
  NO  → Composition     (Room without House = meaningless)

Question 2: Can the PART belong to MULTIPLE wholes?
  YES → Aggregation     (Song in multiple Playlists)
  NO  → Composition     (OrderLineItem belongs to ONE Order)

Code Pattern Signal

Aggregation:   parts PASSED IN from outside     → addEmployee(emp)
Composition:   parts CREATED internally          → new Room(name, area)

Multiplicity

NotationMeaningExample
1Exactly onePerson → 1 Passport
0..1Zero or oneStudent → 0..1 Advisor
*Zero or moreCustomer → * Orders
1..*One or moreOrder → 1..* LineItems
m..nBetween m and nCar → 3..5 Passengers

9.1.d UML Diagrams

Class Box Anatomy

┌─────────────────────────┐
│      ClassName          │  ← Name
├─────────────────────────┤
│ - privateField: Type    │  ← Attributes
│ + publicField: Type     │     (visibility + name + type)
├─────────────────────────┤
│ + method(p: T): RetType │  ← Methods
│ - helper(): void        │     (visibility + signature)
└─────────────────────────┘

UML Arrows (memorize these)

Association:         A ──────────── B    (solid line)
Aggregation:         A ◇─────────── B    (hollow diamond at whole)
Composition:         A ◆─────────── B    (filled diamond at whole)
Dependency:          A ┄┄┄┄┄┄┄┄┄┄► B    (dashed arrow)
Inheritance:         B ──────────▷  A    (solid + hollow triangle → parent)
Implementation:      B ┄┄┄┄┄┄┄┄▷  A    (dashed + hollow triangle → iface)

Sequence Diagram Components

┌──────┐     ┌──────┐
│ Obj1 │     │ Obj2 │     ← Objects/Actors at top
└──┬───┘     └──┬───┘
   │             │        ← Lifelines (dashed vertical)
   │  message()  │
   │────────────►│        ← Synchronous call (solid arrow)
   │             ┌┤
   │             ││        ← Activation bar (processing)
   │  response   ││
   │◄─ ─ ─ ─ ─ ─┤│        ← Return (dashed line)
   │             └┤
   │             │
   
   Time flows DOWNWARD ↓

When to Use Each

Interviewer says...Draw
"Design the classes for X"Class Diagram
"Walk me through the flow"Sequence Diagram
"Design a parking lot"Class Diagram FIRST, then sequence for key flows

9.1.e LLD Interview Approach

The 6-Step Framework

┌──────────────────────────────────────────────────────────────┐
│  Step │ Action                    │ Time │ Output            │
├───────┼───────────────────────────┼──────┼───────────────────┤
│  1    │ Clarify Requirements      │ 5 min│ Requirement list  │
│  2    │ Identify Entities         │ 5 min│ Entity list       │
│  3    │ Define Classes            │10 min│ Class boxes       │
│  4    │ Establish Relationships   │ 8 min│ Class diagram     │
│  5    │ Define Methods + Code     │10 min│ Core logic        │
│  6    │ Edge Cases + Patterns     │ 7 min│ Discussion        │
│       │                           │      │                   │
│ TOTAL │                           │45 min│                   │
└──────────────────────────────────────────────────────────────┘

Noun-Verb Extraction

Nouns      → Candidate classes    (User, Order, Product)
Verbs      → Candidate methods    (create, cancel, calculate)
Adjectives → Candidate enums      (ACTIVE, PENDING, small, medium, large)
"Types of" → Inheritance          (Car, Truck → Vehicle)

Edge Cases to Always Mention

CategoryExamples
ConcurrencyTwo users book the same seat/spot
Full/EmptyLot is full, queue is empty, stock is zero
Invalid InputNegative amount, null object, wrong type
Payment FailureRetry? Rollback? Partial refund?
Not FoundUser not found, ticket expired, product deleted

Design Patterns to Mention

PatternWhen to Mention
StrategyMultiple algorithms for same task (pricing, sorting, validation)
FactoryCreating different subtypes based on input
ObserverOne change triggers multiple reactions (notifications, display updates)
SingletonOnly one instance should exist (DB pool, config)
DecoratorAdding behavior without modifying existing classes (logging, caching)
StateObject behavior changes based on internal state (order lifecycle)

One-Liner Definitions (20+ terms)

TermOne-liner
LLDCode-level blueprint: classes, methods, relationships, patterns.
HLDSystem-level blueprint: services, databases, infrastructure.
ClassBlueprint for creating objects — defines attributes + methods.
ObjectInstance of a class — a living entity with state and behavior.
EncapsulationBundle data + methods; control access via public methods, private state.
InheritanceChild class reuses parent's code; models "is-a" relationships.
PolymorphismSame interface, different behavior depending on the implementing object.
AbstractionExpose only essential details; hide internal complexity.
InterfaceContract — defines method signatures without implementation.
Abstract classPartial implementation — mix of concrete and abstract methods.
Association"Knows about" — two objects reference each other, both exist independently.
AggregationWeak "has-a" — whole references parts; parts survive whole's destruction.
CompositionStrong "owns-a" — whole creates and owns parts; parts die with whole.
DependencyWeakest relationship — temporary usage in a method (parameter or local).
MultiplicityHow many instances relate: 1, 0..1, , 1.., m..n.
UMLUnified Modeling Language — standardized diagrams for software design.
Class diagramStatic structure — classes, attributes, methods, relationships.
Sequence diagramDynamic behavior — step-by-step object interaction over time.
VisibilityAccess level: + public, - private, # protected, ~ package.
Design patternReusable solution to a common software design problem.
Strategy patternEncapsulate interchangeable algorithms behind a common interface.
Observer patternNotify dependents automatically when state changes.
Factory patternCentralize object creation; caller does not know the concrete type.
SOLIDSingle resp., Open/Closed, Liskov Sub., Interface Seg., Dependency Inv.
God classAnti-pattern: one class doing everything — violates single responsibility.

Interview Quick-Fire Checklist

Before walking into an LLD interview, verify you can:

  • Explain HLD vs LLD in 30 seconds
  • Name and explain all four OOP pillars with examples
  • Distinguish aggregation from composition with the litmus test
  • Draw all 6 UML relationship arrows from memory
  • Follow the 6-step framework without looking at notes
  • Extract classes from a requirements paragraph (noun extraction)
  • Name at least 4 design patterns and when to use each
  • Raise 3+ edge cases for any given LLD problem
  • Draw a class diagram with visibility, multiplicity, and correct arrows
  • Draw a sequence diagram with lifelines, messages, and activation bars

End of 9.1 quick revision.

← Back to 9.1 — LLD Foundations (README)