Design a Train Seat Booking System with Segment-Based Seat Reservations

Quick Overview

Design an in-memory train seat booking system where a seat is reserved per route segment, each date has its own inventory, and every booking is all-or-nothing. It tests interval overlap on stop indices, input validation, booking ID lifetime and cancellation ownership rules.

Design a Train Seat Booking System with Segment-Based Seat Reservations

Company: Zepto

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design a deterministic in-memory train seat booking system. It models trains that run every day, their ordered stops, numbered seats, bookings and cancellations. Calls run one at a time. A seat reserved from stop index `a` to stop index `b` occupies the segments `[a, b)`. A booking that ends at a stop and another booking that starts at that same stop can use the same seat. Each date has its own independent inventory, and a booking succeeds only if the whole request can be reserved (all-or-nothing). A booking ID that was used successfully stays reserved forever, even after it is cancelled. The interview question covered only the segment-based seat model. The method signatures, limits, ID lifetime and validation outcomes below are conventions fixed for this exercise. Concurrency fairness, SQL schema design and HTTP APIs are out of scope. Implement a class `TrainBookingSystem` with these methods: - `addTrain(trainId: int, stations: List[str], seatCount: int) -> bool` registers a train with a positive unique ID, 2 to 50 unique non-empty station names in travel order, and 1 to 100 seats. It returns `false` and changes nothing if any input is invalid. - `findTrains(source: str, destination: str) -> List[int]` returns, in ascending order, the IDs of trains that stop at both stations, which must be distinct, with `source` before `destination`. Seat availability is ignored. It returns `[]` for an unknown or invalid route. - `getAvailableSeats(trainId: int, date: str, source: str, destination: str) -> List[int]` returns, in ascending order, the seat IDs that are free on every segment from `source` to `destination` on that date. It returns `[]` for an invalid train or route. - `book(bookingId: int, userId: int, trainId: int, date: str, source: str, destination: str, seatId: int) -> bool` reserves that exact seat on every segment of the route for that date. It needs positive booking and user IDs, a booking ID never used successfully, a valid train, route and seat, and no overlap with an active booking on that seat. On failure nothing changes. - `cancel(bookingId: int, userId: int) -> bool` frees all segments of an active booking if `userId` is its owner. It returns `false` for an unknown booking, the wrong owner, or a booking that is already cancelled. The booking ID can never be used again. Example 1 shows two trips sharing a seat at a common stop, an overlap being rejected, and a new date starting with every seat free. ```text Input: ["TrainBookingSystem", "addTrain", "addTrain", "addTrain", "findTrains", "book", "book", "book", "getAvailableSeats", "getAvailableSeats", "book"] [[], [7, ["A", "B", "C", "D"], 2], [3, ["C", "B", "A"], 1], [5, ["X", "A", "C"], 1], ["A", "C"], [1, 100, 7, "2024-05-01", "A", "C", 1], [2, 200, 7, "2024-05-01", "B", "D", 1], [3, 200, 7, "2024-05-01", "C", "D", 1], [7, "2024-05-01", "B", "C"], [7, "2024-05-02", "A", "D"], [4, 300, 7, "2024-05-02", "A", "D", 1]] Output: [null, true, true, true, [5, 7], true, false, true, [2], [1, 2], true] Explanation: system = TrainBookingSystem() system.addTrain(7, ["A", "B", "C", "D"], 2) # true system.addTrain(3, ["C", "B", "A"], 1) # true system.addTrain(5, ["X", "A", "C"], 1) # true system.findTrains("A", "C") # [5, 7] (train 3 stops at C before A) system.book(1, 100, 7, "2024-05-01", "A", "C", 1) # true (seat 1 holds segments [0, 2)) system.book(2, 200, 7, "2024-05-01", "B", "D", 1) # false ([1, 3) shares segment 1 with [0, 2)) system.book(3, 200, 7, "2024-05-01", "C", "D", 1) # true ([2, 3) starts where booking 1 ends) system.getAvailableSeats(7, "2024-05-01", "B", "C") # [2] (seat 1 is taken on segment 1) system.getAvailableSeats(7, "2024-05-02", "A", "D") # [1, 2] (a new date has its own inventory) system.book(4, 300, 7, "2024-05-02", "A", "D", 1) # true ``` Example 2 shows input validation, cancellation rules and the lifetime of booking IDs. ```text Input: ["TrainBookingSystem", "addTrain", "addTrain", "addTrain", "addTrain", "book", "book", "cancel", "cancel", "cancel", "book", "book", "findTrains", "getAvailableSeats"] [[], [1, ["P", "Q", "R"], 1], [1, ["S", "T"], 5], [2, ["P", "P"], 3], [0, ["P", "Q"], 3], [10, 42, 1, "2024-06-10", "P", "R", 1], [11, 43, 1, "2024-06-10", "Q", "R", 2], [10, 43], [10, 42], [10, 42], [10, 42, 1, "2024-06-10", "P", "R", 1], [11, 43, 1, "2024-06-10", "P", "R", 1], ["Q", "Q"], [1, "2024-06-10", "R", "P"]] Output: [null, true, false, false, false, true, false, false, true, false, false, true, [], []] Explanation: system = TrainBookingSystem() system.addTrain(1, ["P", "Q", "R"], 1) # true system.addTrain(1, ["S", "T"], 5) # false (train ID 1 already exists) system.addTrain(2, ["P", "P"], 3) # false (duplicate station name) system.addTrain(0, ["P", "Q"], 3) # false (train ID must be positive) system.book(10, 42, 1, "2024-06-10", "P", "R", 1) # true system.book(11, 43, 1, "2024-06-10", "Q", "R", 2) # false (train 1 has only seat 1) system.cancel(10, 43) # false (user 43 does not own booking 10) system.cancel(10, 42) # true system.cancel(10, 42) # false (already cancelled) system.book(10, 42, 1, "2024-06-10", "P", "R", 1) # false (booking ID 10 was used before) system.book(11, 43, 1, "2024-06-10", "P", "R", 1) # true (ID 11 never succeeded, and seat 1 is free again) system.findTrains("Q", "Q") # [] (source and destination must differ) system.getAvailableSeats(1, "2024-06-10", "R", "P") # [] (R comes after P on train 1) ``` ```hint Stops to segments Map each station name to its stop index. A trip then becomes a range of segment indices, and the shared-stop rule tells you which ends of that range are open. ``` ```hint Checks before writes In `book`, list every check a request must pass and every record a success creates. Ask which of those records a failed call must leave untouched, including the record of spent booking IDs. ``` ### Constraints & Assumptions - `1 <= trainId` for a valid train. Zero or negative IDs may appear and must be rejected. - `2 <= stations.length <= 50`. Station names are non-empty, unique within a train and case-sensitive. - `1 <= seatCount <= 100`, and seats are numbered `1..seatCount`. - At most 100 trains and 2000 method calls in total. - `date` is always a valid ISO date string such as `"2024-05-01"`. - Booking and user IDs must be positive for a successful booking. Invalid values may appear in tests. - Calls run one at a time. ### Clarifying Questions to Ask - Does a date need to be opened before it can be booked, or does every valid date start with all seats free? - Is a booking always for one seat, or should one booking cover several passengers? - Can a user cancel part of a trip (a shorter sub-route), or does cancellation always free the whole booking? - Can a train be removed or its stops changed after bookings exist for it? ### What a Strong Answer Covers - A data model that separates train definitions (stop order, station index, seat count), occupancy per train, date and seat, and a permanent booking record keyed by booking ID. - A correct overlap test on half-open segment ranges, so trips that meet at a stop share a seat and trips that share a segment do not. - Validation of every input in `addTrain` and `book` before any write, so a failed call changes nothing and a booking ID is spent only on success. - Cancellation that checks ownership and active status, frees the seat's segments, and keeps the ID unusable afterwards. - Sorted outputs and the cost of each operation under the stated limits. ### Follow-up Questions - How would you make `getAvailableSeats` faster if a train had many more seats and stops and each date carried thousands of bookings? - How would you support one booking for several passengers that must all get seats, or none of them? - If calls could run at the same time, where would you put locks so that two users cannot reserve the same seat segment? - When the user does not pick a seat, how would you choose one so that long free stretches stay available for longer trips?

Overview: Design an in-memory train seat booking system where a seat is reserved per route segment, each date has its own inventory, and every booking is all-or-nothing. It tests interval overlap on stop indices, input validation, booking ID lifetime and cancellation ownership rules.

Zepto logo
Zepto
Nov 25, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design a deterministic in-memory train seat booking system. It models trains that run every day, their ordered stops, numbered seats, bookings and cancellations. Calls run one at a time.

A seat reserved from stop index a to stop index b occupies the segments [a, b). A booking that ends at a stop and another booking that starts at that same stop can use the same seat. Each date has its own independent inventory, and a booking succeeds only if the whole request can be reserved (all-or-nothing). A booking ID that was used successfully stays reserved forever, even after it is cancelled.

The interview question covered only the segment-based seat model. The method signatures, limits, ID lifetime and validation outcomes below are conventions fixed for this exercise. Concurrency fairness, SQL schema design and HTTP APIs are out of scope.

Implement a class TrainBookingSystem with these methods:

  • addTrain(trainId: int, stations: List[str], seatCount: int) -> bool registers a train with a positive unique ID, 2 to 50 unique non-empty station names in travel order, and 1 to 100 seats. It returns false and changes nothing if any input is invalid.
  • findTrains(source: str, destination: str) -> List[int] returns, in ascending order, the IDs of trains that stop at both stations, which must be distinct, with source before destination . Seat availability is ignored. It returns [] for an unknown or invalid route.
  • getAvailableSeats(trainId: int, date: str, source: str, destination: str) -> List[int] returns, in ascending order, the seat IDs that are free on every segment from source to destination on that date. It returns [] for an invalid train or route.
  • book(bookingId: int, userId: int, trainId: int, date: str, source: str, destination: str, seatId: int) -> bool reserves that exact seat on every segment of the route for that date. It needs positive booking and user IDs, a booking ID never used successfully, a valid train, route and seat, and no overlap with an active booking on that seat. On failure nothing changes.
  • cancel(bookingId: int, userId: int) -> bool frees all segments of an active booking if userId is its owner. It returns false for an unknown booking, the wrong owner, or a booking that is already cancelled. The booking ID can never be used again.

Example 1 shows two trips sharing a seat at a common stop, an overlap being rejected, and a new date starting with every seat free.

Input:
["TrainBookingSystem", "addTrain", "addTrain", "addTrain", "findTrains", "book", "book", "book", "getAvailableSeats", "getAvailableSeats", "book"]
[[], [7, ["A", "B", "C", "D"], 2], [3, ["C", "B", "A"], 1], [5, ["X", "A", "C"], 1], ["A", "C"], [1, 100, 7, "2024-05-01", "A", "C", 1], [2, 200, 7, "2024-05-01", "B", "D", 1], [3, 200, 7, "2024-05-01", "C", "D", 1], [7, "2024-05-01", "B", "C"], [7, "2024-05-02", "A", "D"], [4, 300, 7, "2024-05-02", "A", "D", 1]]

Output: [null, true, true, true, [5, 7], true, false, true, [2], [1, 2], true]

Explanation:
system = TrainBookingSystem()
system.addTrain(7, ["A", "B", "C", "D"], 2)             # true
system.addTrain(3, ["C", "B", "A"], 1)                  # true
system.addTrain(5, ["X", "A", "C"], 1)                  # true
system.findTrains("A", "C")                             # [5, 7]  (train 3 stops at C before A)
system.book(1, 100, 7, "2024-05-01", "A", "C", 1)       # true    (seat 1 holds segments [0, 2))
system.book(2, 200, 7, "2024-05-01", "B", "D", 1)       # false   ([1, 3) shares segment 1 with [0, 2))
system.book(3, 200, 7, "2024-05-01", "C", "D", 1)       # true    ([2, 3) starts where booking 1 ends)
system.getAvailableSeats(7, "2024-05-01", "B", "C")     # [2]     (seat 1 is taken on segment 1)
system.getAvailableSeats(7, "2024-05-02", "A", "D")     # [1, 2]  (a new date has its own inventory)
system.book(4, 300, 7, "2024-05-02", "A", "D", 1)       # true

Example 2 shows input validation, cancellation rules and the lifetime of booking IDs.

Input:
["TrainBookingSystem", "addTrain", "addTrain", "addTrain", "addTrain", "book", "book", "cancel", "cancel", "cancel", "book", "book", "findTrains", "getAvailableSeats"]
[[], [1, ["P", "Q", "R"], 1], [1, ["S", "T"], 5], [2, ["P", "P"], 3], [0, ["P", "Q"], 3], [10, 42, 1, "2024-06-10", "P", "R", 1], [11, 43, 1, "2024-06-10", "Q", "R", 2], [10, 43], [10, 42], [10, 42], [10, 42, 1, "2024-06-10", "P", "R", 1], [11, 43, 1, "2024-06-10", "P", "R", 1], ["Q", "Q"], [1, "2024-06-10", "R", "P"]]

Output: [null, true, false, false, false, true, false, false, true, false, false, true, [], []]

Explanation:
system = TrainBookingSystem()
system.addTrain(1, ["P", "Q", "R"], 1)                  # true
system.addTrain(1, ["S", "T"], 5)                       # false   (train ID 1 already exists)
system.addTrain(2, ["P", "P"], 3)                       # false   (duplicate station name)
system.addTrain(0, ["P", "Q"], 3)                       # false   (train ID must be positive)
system.book(10, 42, 1, "2024-06-10", "P", "R", 1)       # true
system.book(11, 43, 1, "2024-06-10", "Q", "R", 2)       # false   (train 1 has only seat 1)
system.cancel(10, 43)                                   # false   (user 43 does not own booking 10)
system.cancel(10, 42)                                   # true
system.cancel(10, 42)                                   # false   (already cancelled)
system.book(10, 42, 1, "2024-06-10", "P", "R", 1)       # false   (booking ID 10 was used before)
system.book(11, 43, 1, "2024-06-10", "P", "R", 1)       # true    (ID 11 never succeeded, and seat 1 is free again)
system.findTrains("Q", "Q")                             # []      (source and destination must differ)
system.getAvailableSeats(1, "2024-06-10", "R", "P")     # []      (R comes after P on train 1)

Constraints & Assumptions

  • 1 <= trainId for a valid train. Zero or negative IDs may appear and must be rejected.
  • 2 <= stations.length <= 50 . Station names are non-empty, unique within a train and case-sensitive.
  • 1 <= seatCount <= 100 , and seats are numbered 1..seatCount .
  • At most 100 trains and 2000 method calls in total.
  • date is always a valid ISO date string such as "2024-05-01" .
  • Booking and user IDs must be positive for a successful booking. Invalid values may appear in tests.
  • Calls run one at a time.

Clarifying Questions to Ask Guidance

  • Does a date need to be opened before it can be booked, or does every valid date start with all seats free?
  • Is a booking always for one seat, or should one booking cover several passengers?
  • Can a user cancel part of a trip (a shorter sub-route), or does cancellation always free the whole booking?
  • Can a train be removed or its stops changed after bookings exist for it?

What a Strong Answer Covers Guidance

  • A data model that separates train definitions (stop order, station index, seat count), occupancy per train, date and seat, and a permanent booking record keyed by booking ID.
  • A correct overlap test on half-open segment ranges, so trips that meet at a stop share a seat and trips that share a segment do not.
  • Validation of every input in addTrain and book before any write, so a failed call changes nothing and a booking ID is spent only on success.
  • Cancellation that checks ownership and active status, frees the seat's segments, and keeps the ID unusable afterwards.
  • Sorted outputs and the cost of each operation under the stated limits.

Follow-up Questions Guidance

  • How would you make getAvailableSeats faster if a train had many more seats and stops and each date carried thousands of bookings?
  • How would you support one booking for several passengers that must all get seats, or none of them?
  • If calls could run at the same time, where would you put locks so that two users cannot reserve the same seat segment?
  • When the user does not pick a seat, how would you choose one so that long free stretches stay available for longer trips?