Skip to content

LLD & OOP Design

LLD (low-level design) rounds test whether you can turn a fuzzy problem into clean classes, interfaces and relationships — and write some of the code. Many Indian product companies (and service companies for SDE-1) use LLD instead of HLD for freshers.

Language: TypeScript is fine if the role is JS/full-stack. Ask: “Is it okay if I use TypeScript?” — the concepts map 1:1 to Java.

1. Clarify requirements → list 4–6 features, cut the rest
2. Identify entities → nouns become classes (Vehicle, Spot, Ticket…)
3. Relationships → has-a (composition) vs is-a (inheritance)
4. Behaviours / methods → verbs become methods (park(), unpark())
5. Key design decisions → which patterns, where's the extensibility
6. Code the core flow → one or two main methods fully
7. Edge cases + concurrency → full lot, double booking, invalid input

Requirements (clarify): multiple floors; spot sizes (small/medium/large); vehicle types (bike, car, truck); issue ticket on entry; compute fee on exit; show availability.

Entities: ParkingLot, Floor, Spot, Vehicle, Ticket, PricingStrategy, SpotAllocationStrategy.

enum VehicleType { Bike, Car, Truck }
enum SpotSize { Small, Medium, Large }
const SIZE_FOR: Record<VehicleType, SpotSize> = {
[VehicleType.Bike]: SpotSize.Small,
[VehicleType.Car]: SpotSize.Medium,
[VehicleType.Truck]: SpotSize.Large,
};
class Vehicle {
constructor(public readonly plate: string, public readonly type: VehicleType) {}
}
class Spot {
private vehicle: Vehicle | null = null;
constructor(public readonly id: string, public readonly size: SpotSize) {}
isFree() { return this.vehicle === null; }
canFit(v: Vehicle) { return this.isFree() && this.size >= SIZE_FOR[v.type]; }
assign(v: Vehicle) { this.vehicle = v; }
release() { this.vehicle = null; }
}
class Floor {
constructor(public readonly level: number, public readonly spots: Spot[]) {}
}
class Ticket {
constructor(
public readonly id: string,
public readonly vehicle: Vehicle,
public readonly spot: Spot,
public readonly entryTime: Date,
) {}
}
// Strategy pattern: pricing can change without touching ParkingLot
interface PricingStrategy { calculate(ticket: Ticket, exit: Date): number; }
class HourlyPricing implements PricingStrategy {
constructor(private rates: Record<VehicleType, number>) {}
calculate(t: Ticket, exit: Date) {
const hours = Math.ceil((exit.getTime() - t.entryTime.getTime()) / 3_600_000);
return Math.max(1, hours) * this.rates[t.vehicle.type];
}
}
interface SpotAllocationStrategy { find(floors: Floor[], v: Vehicle): Spot | null; }
class NearestFirst implements SpotAllocationStrategy {
find(floors: Floor[], v: Vehicle) {
for (const f of floors) for (const s of f.spots) if (s.canFit(v)) return s;
return null;
}
}
class ParkingLot {
private active = new Map<string, Ticket>(); // ticketId -> Ticket
constructor(
private floors: Floor[],
private pricing: PricingStrategy,
private allocator: SpotAllocationStrategy,
) {}
park(v: Vehicle): Ticket {
const spot = this.allocator.find(this.floors, v);
if (!spot) throw new Error("Parking full for this vehicle type");
spot.assign(v);
const ticket = new Ticket(crypto.randomUUID(), v, spot, new Date());
this.active.set(ticket.id, ticket);
return ticket;
}
unpark(ticketId: string): number {
const t = this.active.get(ticketId);
if (!t) throw new Error("Invalid ticket");
const fee = this.pricing.calculate(t, new Date());
t.spot.release();
this.active.delete(ticketId);
return fee;
}
}

Talking points: Strategy for pricing and allocation (open/closed); enums for types; for multiple entry gates, park must be atomic (lock per spot or a DB transaction) so two gates don’t assign the same spot; availability count per floor can be cached and updated on park/unpark.


Requirements: get(key) and put(key, value) in O(1); evict least recently used when capacity exceeded.

Idea: HashMap (key → node) + doubly linked list (most recent at head). In JS, a Map preserves insertion order, giving a neat short version — but be ready to write the linked list version, as interviewers often ask for it.

// Short version using Map's insertion order
class LRUCache<K, V> {
private map = new Map<K, V>();
constructor(private capacity: number) {}
get(key: K): V | undefined {
if (!this.map.has(key)) return undefined;
const val = this.map.get(key)!;
this.map.delete(key); // move to most-recent position
this.map.set(key, val);
return val;
}
put(key: K, val: V) {
if (this.map.has(key)) this.map.delete(key);
else if (this.map.size >= this.capacity) {
const oldest = this.map.keys().next().value as K; // first = least recent
this.map.delete(oldest);
}
this.map.set(key, val);
}
}
// Classic version: hashmap + doubly linked list with sentinels
class Node<K, V> {
prev: Node<K, V> | null = null;
next: Node<K, V> | null = null;
constructor(public key: K, public val: V) {}
}
class LRU<K, V> {
private map = new Map<K, Node<K, V>>();
private head = new Node<K, V>(null as K, null as V); // most recent after head
private tail = new Node<K, V>(null as K, null as V); // least recent before tail
constructor(private capacity: number) {
this.head.next = this.tail; this.tail.prev = this.head;
}
private remove(n: Node<K, V>) { n.prev!.next = n.next; n.next!.prev = n.prev; }
private addFront(n: Node<K, V>) {
n.next = this.head.next; n.prev = this.head;
this.head.next!.prev = n; this.head.next = n;
}
get(key: K): V | undefined {
const n = this.map.get(key);
if (!n) return undefined;
this.remove(n); this.addFront(n);
return n.val;
}
put(key: K, val: V) {
const existing = this.map.get(key);
if (existing) { existing.val = val; this.remove(existing); this.addFront(existing); return; }
if (this.map.size === this.capacity) {
const lru = this.tail.prev!;
this.remove(lru); this.map.delete(lru.key);
}
const n = new Node(key, val);
this.addFront(n); this.map.set(key, n);
}
}

Talking points: sentinel nodes remove null checks; extensions — TTL per entry, thread safety (lock in Java; JS is single-threaded per isolate), LFU variant, and where LRU is used in real life (Redis allkeys-lru, browser caches).


3. BookMyShow — Seat Booking (concurrency!)

Section titled “3. BookMyShow — Seat Booking (concurrency!)”

Requirements: list movies/shows by city; view seat map for a show; select seats, hold them for ~5–10 min while paying; confirm on payment; release on timeout/failure. No double booking.

Entities: Movie, Theatre, Screen, Show, Seat, ShowSeat (seat state per show), Booking, Payment, User.

enum SeatStatus { Available, Held, Booked }
enum BookingStatus { Pending, Confirmed, Cancelled, Expired }
class ShowSeat {
status = SeatStatus.Available;
heldBy: string | null = null;
holdExpiresAt: Date | null = null;
constructor(public readonly showId: string, public readonly seatId: string, public price: number) {}
}
class Booking {
status = BookingStatus.Pending;
constructor(
public readonly id: string,
public readonly userId: string,
public readonly showId: string,
public readonly seatIds: string[],
public readonly amount: number,
) {}
}
interface SeatLockProvider {
hold(showId: string, seatIds: string[], userId: string, ttlMs: number): boolean; // all-or-nothing
release(showId: string, seatIds: string[], userId: string): void;
isHeldBy(showId: string, seatId: string, userId: string): boolean;
}
class BookingService {
constructor(private locks: SeatLockProvider, private payments: PaymentGateway) {}
async startBooking(userId: string, showId: string, seatIds: string[]): Promise<Booking> {
if (!this.locks.hold(showId, seatIds, userId, 10 * 60_000))
throw new Error("Some seats are no longer available");
const amount = /* sum seat prices */ 0;
return new Booking(crypto.randomUUID(), userId, showId, seatIds, amount);
}
async confirm(booking: Booking, paymentToken: string) {
// re-check hold still valid, then charge, then mark Booked in one transaction
const ok = booking.seatIds.every(s => this.locks.isHeldBy(booking.showId, s, booking.userId));
if (!ok) { booking.status = BookingStatus.Expired; throw new Error("Hold expired"); }
await this.payments.charge(booking.amount, paymentToken, /* idempotencyKey */ booking.id);
booking.status = BookingStatus.Confirmed;
// persist ShowSeat.status = Booked
}
}
interface PaymentGateway { charge(amount: number, token: string, idempotencyKey: string): Promise<void>; }

How to prevent double booking — the core of this question

Approach How Notes
Pessimistic lock (DB) SELECT ... FROM show_seats WHERE show_id=? AND seat_id IN (...) FOR UPDATE inside a transaction; check all Available; update to Held Simple, correct; locks held briefly
Optimistic (conditional update) UPDATE show_seats SET status='HELD', held_by=?, hold_expires_at=now()+10min WHERE show_id=? AND seat_id IN (...) AND (status='AVAILABLE' OR hold_expires_at < now()) → check affected rows == requested seats, else rollback No long locks; great default answer
Redis lock with TTL SET seat:{show}:{seat} user NX PX 600000 per seat Fast, auto-expires holds; DB still the final source of truth
Unique constraint UNIQUE(show_id, seat_id) on confirmed bookings Last line of defence

Say: “Holds expire automatically (TTL or hold_expires_at) so abandoned checkouts free seats. Payment uses the booking ID as an idempotency key, and if payment succeeds but the hold expired, we refund.”

Also: acquire seat locks in sorted order to avoid deadlocks when two users pick overlapping seats.


Requirements: N elevators, M floors; hall calls (up/down buttons on a floor) and car calls (floor buttons inside); assign a request to the best elevator.

enum Direction { Up, Down, Idle }
class Elevator {
current = 0;
direction = Direction.Idle;
private upStops = new Set<number>();
private downStops = new Set<number>();
constructor(public readonly id: number) {}
addStop(floor: number) { (floor >= this.current ? this.upStops : this.downStops).add(floor); }
step() { /* move one floor in direction; open doors if stop; switch direction when no stops ahead */ }
}
interface Scheduler { pick(elevators: Elevator[], floor: number, dir: Direction): Elevator; }
class NearestCarScheduler implements Scheduler {
pick(es: Elevator[], floor: number, dir: Direction) {
// prefer idle or same-direction elevators moving towards the floor, then nearest
return es.reduce((best, e) =>
Math.abs(e.current - floor) < Math.abs(best.current - floor) ? e : best);
}
}
class ElevatorController {
constructor(private elevators: Elevator[], private scheduler: Scheduler) {}
hallCall(floor: number, dir: Direction) { this.scheduler.pick(this.elevators, floor, dir).addStop(floor); }
}

Talking points: SCAN/LOOK algorithm (keep going in one direction while there are stops, like a disk head); State pattern for elevator states (Moving, Idle, DoorsOpen, Maintenance); Strategy for scheduler.


Q: Singleton — what, when, and a JS example?

Exactly one instance shared app-wide: DB client, logger, config. In Node, a module export is effectively a singleton because modules are cached.

class Db {
private static instance: Db | null = null;
private constructor() {}
static get() { return (this.instance ??= new Db()); }
}
// or simply: export const db = drizzle(pool);

Caveats: global state hurts testing; in Next.js dev, hot reload can create multiple instances — the common fix is caching on globalThis. In Workers, don’t keep request-specific state in module scope.

Q: Factory — what and example?

Centralises object creation so callers don’t new concrete classes.

interface Notifier { send(to: string, msg: string): Promise<void>; }
class EmailNotifier implements Notifier { async send() { /* ... */ } }
class SmsNotifier implements Notifier { async send() { /* ... */ } }
function createNotifier(channel: "email" | "sms"): Notifier {
switch (channel) {
case "email": return new EmailNotifier();
case "sms": return new SmsNotifier();
}
}

From projects: Seqtto document generation — createDocument("certificate" | "offer_letter") returning the right PDF template builder.

Q: Observer — what and example?

Subjects notify subscribers when something happens; publishers don’t know who listens. Node’s EventEmitter, DOM events, Zustand subscriptions, Socket.io, pub/sub all use it.

type Listener<T> = (data: T) => void;
class Emitter<T> {
private listeners = new Set<Listener<T>>();
subscribe(l: Listener<T>) { this.listeners.add(l); return () => this.listeners.delete(l); }
emit(data: T) { this.listeners.forEach(l => l(data)); }
}
const videoStatus = new Emitter<{ id: string; status: string }>();
videoStatus.subscribe(e => io.to(e.id).emit("status", e.status)); // Vigil
Q: Strategy — what and example?

Swap an algorithm at runtime behind a common interface. Removes big if/else chains; obeys open/closed.

interface ScoringStrategy { score(correct: boolean, timeMs: number): number; }
const flat: ScoringStrategy = { score: c => (c ? 10 : 0) };
const speedBonus: ScoringStrategy = { score: (c, t) => (c ? 10 + Math.max(0, 5 - t / 1000) : 0) };
class Quest { constructor(private scoring: ScoringStrategy) {} }

From projects: Calcimate quests could use different scoring strategies; parking lot pricing; rate-limiter algorithms.

Q: Chain of Responsibility / middleware — what and example?

A request passes through a chain of handlers; each can handle it, modify it, or pass it on (next()). Express/Hono middleware is exactly this.

type Ctx = { user?: { role: string }; headers: Record<string, string> };
type Middleware = (ctx: Ctx, next: () => Promise<void>) => Promise<void>;
const auth: Middleware = async (ctx, next) => {
if (!ctx.headers.authorization) throw new Error("401");
ctx.user = { role: "Editor" }; // verify JWT here
await next();
};
const requireRole = (role: string): Middleware => async (ctx, next) => {
if (ctx.user?.role !== role) throw new Error("403");
await next();
};
async function run(ctx: Ctx, chain: Middleware[], i = 0): Promise<void> {
if (i < chain.length) await chain[i](ctx, () => run(ctx, chain, i + 1));
}

From projects: Vigil’s JWT + RBAC middleware (authenticate → requireRole('Admin') → handler).

Q: Other patterns worth one line each?
  • Adapter — wrap an incompatible interface (e.g. unify NSFWJS and Clarifai behind ModerationProvider).
  • Decorator — add behaviour without changing the class (logging/caching wrappers, HOCs).
  • Builder — construct complex objects step by step (query builders like Drizzle, PDF builders).
  • State — object changes behaviour with internal state (elevator, video status machine).
  • Repository — abstract data access behind an interface (UserRepository), easy to mock.
Q: SOLID in one line each?
  • Single responsibility — one reason to change per class.
  • Open/closed — extend with new classes, don’t edit existing ones.
  • Liskov substitution — subclasses must work wherever the parent is expected.
  • Interface segregation — small specific interfaces over one fat one.
  • Dependency inversion — depend on abstractions (PaymentGateway), inject concretions.
Q: Composition vs inheritance — which do you prefer?

Prefer composition: build behaviour by combining objects (ParkingLot has a PricingStrategy) rather than deep class hierarchies. Inheritance is fine for true is-a relationships with shared behaviour, but deep trees become rigid. React itself favours composition.