Episode 9 — System Design / 9.1 — LLD Foundations

9.1 — Exercise Questions: LLD Foundations

Practice questions for all five subtopics in Section 9.1. Mix of short-answer, code, diagram, and design exercises. Try each without peeking at the hints first.

How to use this material (instructions)

  1. Read lessons in orderREADME.md, then 9.1.a9.1.e.
  2. Answer closed-book first — only open hints after a real attempt.
  3. Code it — actually write the classes in TypeScript or JavaScript; do not just read.
  4. Draw it — sketch class diagrams and sequence diagrams on paper or a whiteboard.
  5. Redo misses — retry wrong items the next day.
  6. Interview prep — pair with 9.1-Interview-Questions.md for polished model answers.

9.1.a — What Is LLD (Q1–Q8)

Q1. In your own words, define Low-Level Design. How does it differ from writing code directly?

Q2. Create a comparison table with at least 6 rows contrasting HLD and LLD. Include: scope, audience, artifacts, decisions, tools, and example questions.

Q3. Name five components of a good LLD. For each, write one sentence explaining why it matters.

Q4. Scenario: Your team is building a new notification service. A junior developer says "Let's just start coding — we'll figure out the classes as we go." Explain why an LLD step first would save time. Give a concrete example of what could go wrong without it.

Q5. List at least four things an interviewer evaluates during an LLD interview round. Which one do you think is most important, and why?

Q6. Explain the concept of "separation of concerns" in LLD. Give an example of a badly designed class that violates this principle and show how to split it.

Q7. What does "depend on abstractions, not concretions" mean? Write a short TypeScript example showing the wrong way (depending on a concrete class) and the right way (depending on an interface).

Q8. Scenario: You are given a class UserManager that handles user registration, login, password hashing, email verification, profile updates, and activity logging. Identify the violations and propose a better class breakdown.


9.1.b — OOP Fundamentals (Q9–Q20)

Q9. Explain the difference between a class and an object using a real-world analogy that is NOT the car/blueprint example.

Q10. What is the purpose of a constructor in a class? What happens if you do not define one in JavaScript?

Q11. Write a TypeScript BankAccount class with:

  • Private fields: accountNumber, ownerName, balance
  • Public methods: deposit(amount), withdraw(amount), getBalance(), getStatement()
  • Proper validation (no negative deposits, no overdraft)
  • A readonly field for the account creation date

Q12. Explain encapsulation without using the word "hide." How does it differ from simply making fields private?

Q13. Write a JavaScript class hierarchy for a shape calculator:

  • Base class Shape with an abstract-like area() and perimeter() method
  • Subclasses: Circle, Rectangle, Triangle
  • Each subclass implements area() and perimeter() with the correct formulas
  • Test polymorphism by creating an array of shapes and computing total area

Q14. Compare compile-time polymorphism and runtime polymorphism. Which one does JavaScript natively support? How does TypeScript add support for the other?

Q15. What is the difference between an abstract class and an interface in TypeScript? Create a table with at least 5 comparison rows (constructor, state, multiple inheritance, implementation, use case).

Q16. Write a TypeScript example demonstrating all four pillars of OOP in a single mini-system (e.g., a simple notification system or a vehicle rental system). Label each pillar in comments.

Q17. Explain why "favor composition over inheritance" is a common recommendation. Give an example where inheritance causes problems and composition solves them.

Q18. What are access modifiers in TypeScript? List all four (public, private, protected, readonly) and provide a scenario where each is the correct choice.

Q19. Code exercise: Implement a Logger class hierarchy:

  • Abstract base Logger with a log(level, message) method
  • Concrete: ConsoleLogger, FileLogger, JSONLogger
  • Each formats the output differently
  • Write a function that accepts a Logger[] and logs the same message to all — demonstrating polymorphism

Q20. Comparison exercise: Rewrite the same mini-program (a user registration function) in both procedural style and OOP style. Explain 3 specific advantages the OOP version has.


9.1.c — Class Relationships (Q21–Q30)

Q21. Fill in the blank: "Aggregation is a ___ form of association, while composition is a ___ form."

Q22. For each pair below, identify the relationship type (association, aggregation, composition, dependency, inheritance, implementation):

  1. Car and Engine
  2. University and Student
  3. Order and OrderLineItem
  4. Dog and Animal
  5. EmailService and SMTPClient (EmailService uses SMTPClient in one method)
  6. ArrayList and Iterable (in Java terms)
  7. Library and Book
  8. Browser and Tab

Q23. Write the litmus test for deciding between aggregation and composition. Apply it to: (a) Playlist and Song, (b) Human and Heart, (c) Company and Employee.

Q24. Code exercise: Implement an aggregation example and a composition example in TypeScript. The aggregation example should show the part surviving the whole's destruction. The composition example should show the part being created internally.

Q25. Draw an ASCII class diagram for a Hospital Management System with at least 6 classes. Include: Hospital, Department, Doctor, Patient, Appointment, MedicalRecord. Label every relationship with its type and multiplicity.

Q26. Explain the difference between dependency and association using code. Show the same two classes — once with a dependency relationship and once with an association.

Q27. What is multiplicity? Draw examples of 1:1, 1:N, and M:N relationships with real-world entities. For the M:N example, show how you would resolve it with a junction class.

Q28. Scenario: A colleague designs a system where Car extends Engine. Explain why this is wrong. What relationship should Car and Engine have? Which OOP principle is violated?

Q29. Write a TypeScript example showing a class that uses both inheritance (extends) and implementation (implements) simultaneously. Explain when this pattern is useful.

Q30. Design exercise: For a Food Delivery App, identify the relationships between: Customer, Restaurant, Menu, MenuItem, Order, DeliveryDriver, Payment. Draw the class diagram with correct relationship types and multiplicity.


9.1.d — UML Diagrams (Q31–Q38)

Q31. Draw a UML class box for a Product class with:

  • Private fields: id, name, price, stockCount
  • Public methods: getPrice(), isInStock(), reduceStock(qty)
  • A protected method: validatePrice(price)
  • Use correct UML visibility symbols (+, -, #)

Q32. What is the difference between a solid line and a dashed line in UML class diagrams? List all 6 relationship arrow types with their line style and arrowhead shape.

Q33. Draw a complete UML class diagram for an Online Movie Ticket Booking System with at least 5 classes. Include: Movie, Theater, Screen, Seat, Booking, Customer. Show visibility, key attributes, key methods, relationships, and multiplicity.

Q34. Draw a UML sequence diagram for the following scenario: "A user searches for a movie, selects a showtime, picks seats, and makes a payment." Include at least 4 objects (User, SearchService, BookingService, PaymentService).

Q35. What are activation bars in a sequence diagram? Draw a mini sequence diagram that includes: (a) a synchronous call, (b) a self-call, (c) a return message.

Q36. Explain when you would draw a class diagram vs a sequence diagram in an interview. Give 3 example interview questions where each is more appropriate.

Q37. Speed drill: Without looking at notes, draw the UML symbols for: (a) composition, (b) aggregation, (c) inheritance, (d) interface implementation, (e) dependency, (f) directed association. Time yourself — aim for under 60 seconds.

Q38. Diagram exercise: Take any class diagram you drew above and write the corresponding TypeScript code. Then take any sequence diagram and trace through it step-by-step, writing the function calls that would execute.


9.1.e — LLD Interview Approach (Q39–Q45)

Q39. List the 6 steps of the LLD interview framework in order. For each step, write: (a) how many minutes to spend, (b) what deliverable you produce.

Q40. Noun extraction drill: From the following requirement, extract all entities: "An elevator system has multiple elevators in a building. Each elevator serves specific floors. Users press buttons to request an elevator. The system dispatches the nearest available elevator. Elevators have a capacity limit and a door that opens and closes."

Q41. Practice interview (timed): Set a 45-minute timer and design a Library Management System. Follow the 6-step framework strictly. Write down your clarifying questions, entity list, class definitions, relationships, core methods, and edge cases.

Q42. Practice interview (timed): Set a 45-minute timer and design a Tic-Tac-Toe Game. Identify: Board, Cell, Player, Game, Move. Define win condition checking logic.

Q43. List 5 common mistakes in LLD interviews and explain how to avoid each one.

Q44. Edge case drill: For each system below, list at least 3 edge cases:

  1. Parking Lot System
  2. Elevator System
  3. Vending Machine
  4. Chess Game
  5. Online Auction System

Q45. Design pattern matching: For each scenario, name the most appropriate design pattern:

  1. Only one instance of a database connection pool should exist
  2. Different discount strategies for different customer types
  3. An order processing pipeline with sequential steps
  4. Real-time notifications when a stock price changes
  5. Creating different types of notifications (email, SMS, push) based on user preference
  6. Adding logging to existing service methods without modifying them

Comprehensive Exercises (Q46–Q50)

Q46. Mega-exercise: Design a complete Hotel Booking System following the 6-step framework. Include: Hotel, Room, RoomType, Guest, Booking, Payment, Staff. Draw the class diagram, write the core classes in TypeScript, and draw a sequence diagram for the "book a room" flow.

Q47. Refactoring exercise: The following code violates multiple OOP principles. Identify each violation and refactor it:

class UserSystem {
  users = [];
  
  createUser(name, email, password) {
    const hashedPwd = require('bcrypt').hashSync(password, 10);
    this.users.push({ name, email, password: hashedPwd, createdAt: new Date() });
    console.log(`User ${name} created`);
    const nodemailer = require('nodemailer');
    // ... send welcome email
    fetch('https://analytics.example.com/track', {
      method: 'POST',
      body: JSON.stringify({ event: 'user_created', name })
    });
  }
  
  login(email, password) { /* ... */ }
  resetPassword(email) { /* ... */ }
  updateProfile(email, data) { /* ... */ }
  deleteUser(email) { /* ... */ }
  generateReport() { /* ... */ }
  sendNewsletter() { /* ... */ }
}

Q48. Diagram translation: Given this ASCII class diagram, write the complete TypeScript code:

┌──────────────────┐
│  <<interface>>   │
│   Playable       │
├──────────────────┤
│ + play(): void   │
│ + pause(): void  │
│ + stop(): void   │
└────────▲─────────┘
         ┆ implements
    ┌────┴────┐
    │         │
┌───┴─────┐  ┌┴──────────┐
│AudioFile │  │VideoFile  │
├─────────┤  ├───────────┤
│-title   │  │-title     │
│-duration│  │-duration  │
│-bitrate │  │-resolution│
├─────────┤  ├───────────┤
│+play()  │  │+play()    │
│+pause() │  │+pause()   │
│+stop()  │  │+stop()    │
└─────────┘  └───────────┘

Q49. Relationship stress test: For each of the following, choose EXACTLY ONE relationship type and defend your choice:

  1. Browser and Extension — Association, Aggregation, or Composition?
  2. Email and Attachment — Association, Aggregation, or Composition?
  3. Smartphone and App — Association, Aggregation, or Composition?
  4. Blog and Comment — Association, Aggregation, or Composition?
  5. Orchestra and Musician — Association, Aggregation, or Composition?

Q50. Full mock interview: Have a friend (or rubber duck) interview you with "Design a Stack Overflow clone." Time: 45 minutes. After, self-evaluate against the interviewer scoring rubric from 9.1.a: Requirement gathering (did you clarify?), Entity identification, Class design, Relationships, Method signatures, Design patterns, Extensibility, Edge cases. Rate yourself 1–5 on each.


Answer Hints

(Short reminders — expand in your own words when studying.)

QHint
Q1LLD = code-level blueprint (classes, methods, relationships). Not the same as coding because it is about STRUCTURE decisions, not implementation details.
Q2HLD: whole system, architects, architecture diagrams. LLD: single module, developers, class diagrams.
Q6One class = one responsibility. Bad: UserManager does auth + profile + email + logging. Good: split into UserService, AuthService, EmailService, Logger.
Q7Wrong: class OrderService { stripe = new StripeProcessor() }. Right: class OrderService { payment: PaymentProcessor }.
Q12Encapsulation = controlling access to data through methods. Not just making fields private — it is about providing a CONTROLLED interface.
Q14JS natively supports runtime (method overriding). TS adds compile-time via overload signatures.
Q15Abstract: can have implementation + state + constructor, single extends. Interface: only contract, no state, multiple implements.
Q17Inheritance: Dog extends Animal then you need FlyingDog. Composition: Dog has-a FlightAbility component — flexible.
Q21Aggregation = "weak" form; Composition = "strong" form.
Q221: Composition, 2: Aggregation, 3: Composition, 4: Inheritance, 5: Dependency, 6: Implementation, 7: Aggregation, 8: Composition.
Q23Can part exist without whole? Can part belong to multiple wholes? (a) Agg — songs exist without playlist, (b) Comp — heart cannot live without human, (c) Agg — employee exists without company.
Q28Car IS-NOT an Engine. Car HAS-A Engine. Use composition. Violated principle: Liskov Substitution / "is-a" test.
Q31- id: str, - name: str, - price: num, - stockCount: num, + getPrice(): num, + isInStock(): bool, + reduceStock(qty: num): void, # validatePrice(price: num): bool.
Q32Solid line: association/aggregation/composition/inheritance. Dashed line: dependency/implementation.
Q391: Clarify (5 min, requirement list), 2: Entities (5 min, entity list), 3: Classes (10 min, class boxes), 4: Relationships (8 min, class diagram), 5: Methods (10 min, code), 6: Edge cases (7 min, discussion).
Q40ElevatorSystem, Elevator, Building, Floor, Button, User, Door. Enums: Direction, ElevatorState.
Q451: Singleton, 2: Strategy, 3: Chain of Responsibility or Template Method, 4: Observer, 5: Factory, 6: Decorator.

← Back to 9.1 — LLD Foundations (README)