Interview Study Guide

Guide / Low-level design

25. Worked LLD solutions (TypeScript)

Created · Updated · 6 min read

Machine-coding rounds (60–90 min) judge: clear entities, extensibility, working code, and handling concurrency. Approach: clarify requirements (5 min) → list entities and relationships → define interfaces → implement the core flow → add tests/demo → discuss extensions.

25.1 LRU cache — O(1) get and put#

Hash map for lookup + doubly linked list for recency (head = most recent, tail = least recent). A JavaScript Map keeps insertion order, which gives a short version; interviewers often want the explicit list, so know both.

class Node<K, V> {
  prev: Node<K, V> | null = null;
  next: Node<K, V> | null = null;
  constructor(public key: K, public value: V) {}
}

export class LRUCache<K, V> {
  private map = new Map<K, Node<K, V>>();
  private head = new Node<K, V>(null as K, null as V); // sentinel: most recent side
  private tail = new Node<K, V>(null as K, null as V); // sentinel: least recent side

  constructor(private capacity: number) {
    if (capacity <= 0) throw new Error("capacity must be > 0");
    this.head.next = this.tail;
    this.tail.prev = this.head;
  }

  get(key: K): V | undefined {
    const node = this.map.get(key);
    if (!node) return undefined;
    this.moveToFront(node);
    return node.value;
  }

  put(key: K, value: V): void {
    const existing = this.map.get(key);
    if (existing) {
      existing.value = value;
      this.moveToFront(existing);
      return;
    }
    if (this.map.size === this.capacity) {
      const lru = this.tail.prev!;
      this.remove(lru);
      this.map.delete(lru.key);
    }
    const node = new Node(key, value);
    this.addToFront(node);
    this.map.set(key, node);
  }

  private addToFront(node: Node<K, V>) {
    node.next = this.head.next;
    node.prev = this.head;
    this.head.next!.prev = node;
    this.head.next = node;
  }
  private remove(node: Node<K, V>) {
    node.prev!.next = node.next;
    node.next!.prev = node.prev;
  }
  private moveToFront(node: Node<K, V>) {
    this.remove(node);
    this.addToFront(node);
  }
}

Extensions to discuss: TTL per entry (store expiresAt, check on get, lazy + periodic cleanup), thread safety in multi-threaded languages (one mutex, or striped locks per shard), LFU variant (frequency buckets), distributed version (consistent hashing over nodes — that’s Redis).

25.2 Parking lot — entities, strategy and extensibility#

Requirements to confirm: multiple floors, spot sizes (small/medium/large), vehicle types (bike/car/truck), tickets on entry, fee on exit by duration and vehicle type, show availability.

enum SpotSize { Small = 1, Medium = 2, Large = 3 }
enum VehicleType { Bike = "BIKE", Car = "CAR", Truck = "TRUCK" }

const REQUIRED_SIZE: Record<VehicleType, SpotSize> = {
  [VehicleType.Bike]: SpotSize.Small,
  [VehicleType.Car]: SpotSize.Medium,
  [VehicleType.Truck]: SpotSize.Large,
};

class Vehicle { constructor(public plate: string, public type: VehicleType) {} }

class Spot {
  vehicle: Vehicle | null = null;
  constructor(public id: string, public floor: number, public size: SpotSize) {}
  fits(v: Vehicle) { return !this.vehicle && this.size >= REQUIRED_SIZE[v.type]; }
}

class Ticket {
  constructor(public id: string, public vehicle: Vehicle, public spot: Spot,
              public entryAt: Date) {}
}

// Strategy pattern: swap allocation and pricing rules without touching ParkingLot (open/closed)
interface SpotAllocator { find(spots: Spot[], v: Vehicle): Spot | undefined }
class NearestSmallestFit implements SpotAllocator {
  find(spots: Spot[], v: Vehicle) {
    return spots.filter(s => s.fits(v))
      .sort((a, b) => a.floor - b.floor || a.size - b.size)[0];
  }
}

interface PricingStrategy { fee(t: Ticket, exitAt: Date): number }
class HourlyPricing implements PricingStrategy {
  constructor(private ratePerHour: Record<VehicleType, number>) {}
  fee(t: Ticket, exitAt: Date) {
    const hours = Math.max(1, Math.ceil((exitAt.getTime() - t.entryAt.getTime()) / 3_600_000));
    return hours * this.ratePerHour[t.vehicle.type];
  }
}

export class ParkingLot {
  private active = new Map<string, Ticket>(); // ticketId -> ticket
  private seq = 0;
  constructor(private spots: Spot[], private allocator: SpotAllocator,
              private pricing: PricingStrategy) {}

  park(v: Vehicle, now = new Date()): Ticket {
    const spot = this.allocator.find(this.spots, v);
    if (!spot) throw new Error("No spot available");
    spot.vehicle = v;
    const ticket = new Ticket(`T${++this.seq}`, v, spot, now);
    this.active.set(ticket.id, ticket);
    return ticket;
  }

  exit(ticketId: string, now = new Date()): number {
    const t = this.active.get(ticketId);
    if (!t) throw new Error("Invalid or already used ticket");
    const fee = this.pricing.fee(t, now);
    t.spot.vehicle = null;
    this.active.delete(ticketId);
    return fee;
  }

  available(size: SpotSize) {
    return this.spots.filter(s => !s.vehicle && s.size === size).length;
  }
}

Talking points: Strategy for allocation and pricing (add EV spots or weekend rates without modifying ParkingLot); single responsibility per class; for many entry gates in a real system, park must be atomic (a lock per lot in memory, or a conditional DB update on the spot row); availability per floor via counters instead of scanning; payment via an adapter interface.

25.3 Movie seat booking with concurrent holds (BookMyShow)#

The point of this problem is concurrency: two users must never book the same seat.

Database design (Postgres):

CREATE TABLE show_seats (
  show_id     BIGINT,
  seat_id     TEXT,
  status      TEXT NOT NULL DEFAULT 'AVAILABLE', -- AVAILABLE | HELD | BOOKED
  held_by     BIGINT,
  hold_until  TIMESTAMPTZ,
  booking_id  BIGINT,
  version     INT NOT NULL DEFAULT 0,
  PRIMARY KEY (show_id, seat_id)
);

-- Hold several seats atomically: succeeds only if ALL are free (or their hold expired)
UPDATE show_seats
SET status = 'HELD', held_by = $user, hold_until = now() + interval '8 minutes',
    version = version + 1
WHERE show_id = $show AND seat_id = ANY($seats)
  AND (status = 'AVAILABLE' OR (status = 'HELD' AND hold_until < now()));
-- In the service: if rows updated != number of seats requested -> ROLLBACK and report conflict

Service logic:

async function holdSeats(db: Db, showId: number, seatIds: string[], userId: number) {
  return db.transaction(async tx => {
    const updated = await tx.execute(HOLD_SQL, { showId, seatIds, userId });
    if (updated.rowCount !== seatIds.length) {
      throw new ConflictError("Some seats were just taken"); // transaction rolls back all holds
    }
    return { holdExpiresInSec: 480 };
  });
}

async function confirmBooking(db: Db, showId: number, seatIds: string[], userId: number,
                              paymentRef: string, idempotencyKey: string) {
  return db.transaction(async tx => {
    // Unique constraint on bookings.idempotency_key makes retries safe
    const booking = await tx.insertBookingIfAbsent({ showId, userId, paymentRef, idempotencyKey });
    if (booking.alreadyExisted) return booking;
    const updated = await tx.execute(
      `UPDATE show_seats SET status='BOOKED', booking_id=$1
       WHERE show_id=$2 AND seat_id = ANY($3) AND status='HELD'
         AND held_by=$4 AND hold_until > now()`,
      [booking.id, showId, seatIds, userId]);
    if (updated.rowCount !== seatIds.length) {
      throw new HoldExpiredError(); // caller refunds the payment
    }
    return booking;
  });
}

Talking points: atomic conditional update instead of read-then-write; holds expire by time, so no cleanup job is needed for correctness (a sweeper only tidies status); payment success after hold expiry triggers refund or re-hold attempt; idempotent confirmation; for blockbuster openings, add a virtual queue and Redis-based holds in front of the DB (same pattern as walkthrough 11.1). Entities for the class diagram: Movie, Theatre, Screen, Show, Seat, ShowSeat, Booking, Payment, User.

25.4 More to practise (same approach)#

Splitwise (expense split strategies, simplify debts with a min-cash-flow greedy), elevator (State pattern, scheduling strategy), rate limiter class (token bucket with injectable clock for tests), in-memory KV store with TTL and transactions, pub/sub with topics and subscribers (Observer), snake & ladder, logger with levels and sinks (Chain of Responsibility).

Finished this page?Mark it done to track your progress across the guide.
Pritam Ghosh · System design & AI engineering study notes