{}DSA Atlas

LLD Case Studies II — Splitwise, BookMyShow, Logger, Games

Expense sharing with split strategies and debt simplification, movie ticket booking with seat holds and concurrency, an extensible logging framework, a pluggable rate limiter, and tic-tac-toe / snake-and-ladder game designs — each with requirements, design decisions and Java/Python code.

Intermediate → Advanced4 interview questions

1. Splitwise (expense sharing)

Requirements

  1. Users and groups; add an expense paid by one (or more) users, split among participants.
  2. Split types: equal, exact amounts, percentages (extensible: shares).
  3. Show balances per user ("you owe Ravi ₹250"), settle up, and simplify debts within a group.

Design

  • Expense(id, paidBy, amount, splits, description); Split(user, amount).
  • Strategy per split type: SplitStrategy.split(amount, participants, params) → validated List<Split>.
  • BalanceSheet: Map<UserPair, Long> or net balance per user.
  • All money in paise (long); deterministic remainder distribution.
interface SplitStrategy { List<Split> split(long amount, List<String> users, List<Long> params); }

record Split(String user, long amount) {}

final class EqualSplit implements SplitStrategy {
    public List<Split> split(long amount, List<String> users, List<Long> ignored) {
        long base = amount / users.size(), remainder = amount % users.size();
        List<Split> out = new ArrayList<>();
        for (int i = 0; i < users.size(); i++)
            out.add(new Split(users.get(i), base + (i < remainder ? 1 : 0)));   // first users absorb the paise
        return out;
    }
}

final class ExactSplit implements SplitStrategy {
    public List<Split> split(long amount, List<String> users, List<Long> exact) {
        if (exact.stream().mapToLong(Long::longValue).sum() != amount)
            throw new IllegalArgumentException("exact amounts must add up to the total");
        List<Split> out = new ArrayList<>();
        for (int i = 0; i < users.size(); i++) out.add(new Split(users.get(i), exact.get(i)));
        return out;
    }
}

final class PercentSplit implements SplitStrategy {
    public List<Split> split(long amount, List<String> users, List<Long> pct) {   // pct in basis points
        if (pct.stream().mapToLong(Long::longValue).sum() != 10_000)
            throw new IllegalArgumentException("percentages must total 100%");
        List<Split> out = new ArrayList<>();
        long allocated = 0;
        for (int i = 0; i < users.size(); i++) {
            long share = (i == users.size() - 1) ? amount - allocated : amount * pct.get(i) / 10_000;
            allocated += share;
            out.add(new Split(users.get(i), share));
        }
        return out;
    }
}

final class ExpenseService {
    private final Map<String, Long> net = new ConcurrentHashMap<>();   // + is owed money, − owes money

    synchronized void addExpense(String paidBy, long amount, List<String> users,
                                 SplitStrategy strategy, List<Long> params) {
        for (Split s : strategy.split(amount, users, params)) {
            net.merge(s.user(), -s.amount(), Long::sum);
        }
        net.merge(paidBy, amount, Long::sum);
    }

    /** Greedy debt simplification: at most n−1 transfers. */
    List<String> settlements() {
        PriorityQueue<Map.Entry<String, Long>> creditors =
            new PriorityQueue<>((a, b) -> Long.compare(b.getValue(), a.getValue()));
        PriorityQueue<Map.Entry<String, Long>> debtors =
            new PriorityQueue<>(Comparator.comparingLong(Map.Entry::getValue));
        net.forEach((u, v) -> {
            if (v > 0) creditors.add(new AbstractMap.SimpleEntry<>(u, v));
            else if (v < 0) debtors.add(new AbstractMap.SimpleEntry<>(u, v));
        });
        List<String> out = new ArrayList<>();
        while (!creditors.isEmpty() && !debtors.isEmpty()) {
            var c = creditors.poll(); var d = debtors.poll();
            long x = Math.min(c.getValue(), -d.getValue());
            out.add(d.getKey() + " pays " + c.getKey() + " " + x);
            if (c.getValue() - x > 0) creditors.add(new AbstractMap.SimpleEntry<>(c.getKey(), c.getValue() - x));
            if (d.getValue() + x < 0) debtors.add(new AbstractMap.SimpleEntry<>(d.getKey(), d.getValue() + x));
        }
        return out;
    }
}
import heapq

def simplify(net: dict[str, int]) -> list[tuple[str, str, int]]:
    creditors = [(-v, u) for u, v in net.items() if v > 0]     # max-heap via negation
    debtors = [(v, u) for u, v in net.items() if v < 0]        # most negative first
    heapq.heapify(creditors); heapq.heapify(debtors)
    out = []
    while creditors and debtors:
        c_amt, c = heapq.heappop(creditors); d_amt, d = heapq.heappop(debtors)
        x = min(-c_amt, -d_amt)
        out.append((d, c, x))
        if -c_amt - x: heapq.heappush(creditors, (c_amt + x, c))
        if -d_amt - x: heapq.heappush(debtors, (d_amt + x, d))
    return out

print(simplify({"asha": 300, "ravi": -100, "meera": -200}))
# [('meera', 'asha', 200), ('ravi', 'asha', 100)]

2. Movie ticket booking (BookMyShow)

Requirements

  1. Cities → cinemas → screens → shows (movie + time); each screen has a seat layout with categories (silver/gold/recliner) and prices.
  2. Users browse shows, view the seat map, hold seats for ~10 minutes, pay, and get a booking.
  3. No double booking under concurrency; holds expire; cancellations and refunds.

Model

City Cinema Screen Seat Show Movie ShowSeatstatus · heldBy · expiry Booking Payment
Seat availability lives on ShowSeat (seat × show), not on Seat.
Java
enum SeatStatus { AVAILABLE, HELD, BOOKED }

final class ShowSeat {
    final String seatId; final long priceMinor;
    SeatStatus status = SeatStatus.AVAILABLE;
    String heldBy; Instant holdExpires;
    ShowSeat(String seatId, long price) { this.seatId = seatId; this.priceMinor = price; }
    boolean isFree(Instant now) {
        return status == SeatStatus.AVAILABLE || (status == SeatStatus.HELD && holdExpires.isBefore(now));
    }
}

final class Show {
    final String id;
    private final Map<String, ShowSeat> seats;
    private final ReentrantLock lock = new ReentrantLock();     // per-show lock: shows don't block each other
    Show(String id, Map<String, ShowSeat> seats) { this.id = id; this.seats = seats; }

    /** All-or-nothing hold. */
    boolean hold(List<String> seatIds, String user, Instant now, Duration ttl) {
        lock.lock();
        try {
            for (String s : seatIds) if (!seats.get(s).isFree(now)) return false;
            for (String s : seatIds) {
                ShowSeat ss = seats.get(s);
                ss.status = SeatStatus.HELD; ss.heldBy = user; ss.holdExpires = now.plus(ttl);
            }
            return true;
        } finally { lock.unlock(); }
    }

    boolean confirm(List<String> seatIds, String user, Instant now) {
        lock.lock();
        try {
            for (String s : seatIds) {
                ShowSeat ss = seats.get(s);
                if (ss.status != SeatStatus.HELD || !user.equals(ss.heldBy) || ss.holdExpires.isBefore(now))
                    return false;                                // hold lost → refund the payment
            }
            seatIds.forEach(s -> seats.get(s).status = SeatStatus.BOOKED);
            return true;
        } finally { lock.unlock(); }
    }
}

final class BookingService {
    Booking book(Show show, List<String> seats, String user, PaymentGateway pay, String idemKey) {
        Instant now = Instant.now();
        if (!show.hold(seats, user, now, Duration.ofMinutes(10)))
            throw new IllegalStateException("some seats are no longer available");
        PaymentResult r = pay.charge(user, total(show, seats), idemKey);   // idempotent
        if (!r.success() || !show.confirm(seats, user, Instant.now())) {
            if (r.success()) pay.refund(r.reference());
            throw new IllegalStateException("booking failed");
        }
        return new Booking(UUID.randomUUID().toString(), show.id, seats, user, r.reference());
    }
    private long total(Show s, List<String> seats) { return 0; /* sum seat prices */ }
}

Scaling this beyond one process (database row conditions, Redis holds, queueing for hot shows) is covered in the ticket booking case study.

3. Logging framework

Java
enum Level { DEBUG, INFO, WARN, ERROR }

record LogRecord(Instant ts, Level level, String logger, String message, String thread) {}

interface Formatter { String format(LogRecord r); }
interface Appender { void append(LogRecord r); }

final class JsonFormatter implements Formatter {
    public String format(LogRecord r) {
        return String.format("{\"ts\":\"%s\",\"level\":\"%s\",\"logger\":\"%s\",\"msg\":\"%s\"}",
                             r.ts(), r.level(), r.logger(), r.message().replace("\"", "\\\""));
    }
}

final class ConsoleAppender implements Appender {
    private final Formatter f;
    ConsoleAppender(Formatter f) { this.f = f; }
    public synchronized void append(LogRecord r) { System.out.println(f.format(r)); }
}

/** Decorator: never block the application thread on I/O. */
final class AsyncAppender implements Appender {
    private final BlockingQueue<LogRecord> q = new ArrayBlockingQueue<>(10_000);
    AsyncAppender(Appender inner) {
        Thread t = new Thread(() -> {
            while (true) {
                try { inner.append(q.take()); } catch (InterruptedException e) { return; }
            }
        }, "log-writer");
        t.setDaemon(true); t.start();
    }
    public void append(LogRecord r) { q.offer(r); }          // drop when full (count drops in a metric)
}

final class Logger {
    private final String name; private volatile Level threshold; private final List<Appender> appenders;
    Logger(String name, Level threshold, List<Appender> appenders) {
        this.name = name; this.threshold = threshold; this.appenders = appenders;
    }
    void log(Level level, Supplier<String> msg) {             // lazy: no string building if disabled
        if (level.ordinal() < threshold.ordinal()) return;
        LogRecord r = new LogRecord(Instant.now(), level, name, msg.get(), Thread.currentThread().getName());
        for (Appender a : appenders) {
            try { a.append(r); } catch (RuntimeException ignored) { /* logging must never crash the app */ }
        }
    }
    void info(Supplier<String> m) { log(Level.INFO, m); }
    void error(Supplier<String> m) { log(Level.ERROR, m); }
}

4. Rate limiter (LLD view)

Java
interface RateLimiter { boolean tryAcquire(String key); }

final class TokenBucketLimiter implements RateLimiter {
    private record Bucket(double tokens, long lastNanos) {}
    private final ConcurrentHashMap<String, Bucket> buckets = new ConcurrentHashMap<>();
    private final double ratePerSec, capacity;
    TokenBucketLimiter(double ratePerSec, double capacity) { this.ratePerSec = ratePerSec; this.capacity = capacity; }

    public boolean tryAcquire(String key) {
        long now = System.nanoTime();
        boolean[] allowed = {false};
        buckets.compute(key, (k, b) -> {                     // atomic per key
            double tokens = b == null ? capacity
                : Math.min(capacity, b.tokens() + (now - b.lastNanos()) / 1e9 * ratePerSec);
            if (tokens >= 1) { tokens -= 1; allowed[0] = true; }
            return new Bucket(tokens, now);
        });
        return allowed[0];
    }
}

// Strategy: SlidingWindowLimiter, FixedWindowLimiter implement the same interface;
// a factory picks one per configuration.

Algorithms and the distributed version: Rate limiting.

5. Games: tic-tac-toe and snake & ladder

Tic-tac-toe with O(1) win detection

Python
class TicTacToe:
    def __init__(self, n: int = 3):
        self.n = n
        self.rows, self.cols = [0] * n, [0] * n
        self.diag = self.anti = 0
        self.board = [[None] * n for _ in range(n)]
        self.moves = 0

    def move(self, r: int, c: int, player: int) -> str:
        if self.board[r][c] is not None:
            raise ValueError("cell occupied")
        self.board[r][c] = player
        self.moves += 1
        d = 1 if player == 1 else -1
        self.rows[r] += d; self.cols[c] += d
        if r == c: self.diag += d
        if r + c == self.n - 1: self.anti += d
        if self.n in (abs(self.rows[r]), abs(self.cols[c]), abs(self.diag), abs(self.anti)):
            return f"player {player} wins"
        return "draw" if self.moves == self.n * self.n else "continue"

Snake & ladder

Python
import random
from dataclasses import dataclass, field

@dataclass
class Board:
    size: int = 100
    jumps: dict[int, int] = field(default_factory=dict)      # snakes (down) and ladders (up) unified

    def land(self, pos: int) -> int:
        return self.jumps.get(pos, pos)

class Dice:
    def __init__(self, count=1, rng=random.Random()):
        self.count, self.rng = count, rng                     # inject RNG for deterministic tests
    def roll(self) -> int:
        return sum(self.rng.randint(1, 6) for _ in range(self.count))

class Game:
    def __init__(self, board: Board, players: list[str], dice: Dice):
        self.board, self.players, self.dice = board, players, dice
        self.pos = {p: 0 for p in players}

    def play(self) -> str:
        turn = 0
        while True:
            p = self.players[turn % len(self.players)]
            nxt = self.pos[p] + self.dice.roll()
            if nxt <= self.board.size:                        # overshoot → stay
                self.pos[p] = self.board.land(nxt)
            if self.pos[p] == self.board.size:
                return p
            turn += 1

game = Game(Board(jumps={14: 4, 17: 7, 3: 22, 8: 30, 98: 28}), ["asha", "ravi"], Dice())
print(game.play(), "wins")

Design points interviewers look for: snakes and ladders unified as jumps, injectable Dice (strategy; deterministic tests), board validation (no cycles, no jump from the last square), extensible rules (multiple dice, "six gives another turn").

Interview questions

0 / 4 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.