Thread-Safe Lowest-Index Seat Allocator

Medium · Software Engineering Fundamentals · Backend Engineer · Online Assessment

Problem Statement

Design a concurrent reservation component for a venue containing n numbered seats indexed from 0 through n - 1. Multiple worker threads will request seats at the same time, and each successful request must receive the smallest index that has not yet been assigned.

Seat assignments are permanent: once an index is handed out, it is never returned to the free pool. Whenever every seat from 0 through n - 1 has already been assigned, any further request must return -1.

Implement both the SeatAllocator class and the driver function seat_allocator:

class SeatAllocator:
    def __init__(self, n: int):
        ...

    def claimSeat(self) -> int:
        ...


def seat_allocator(
    n: int,
    operations: List[str],
    arguments: List[List[int]],
) -> List[int]:
    ...
  • SeatAllocator(n) prepares an allocator managing n seats (0 to n - 1).
  • claimSeat() atomically assigns and returns the smallest unassigned seat index, or -1 when capacity is exhausted. Concurrent callers must never receive duplicate indices or values outside 0 .. n - 1, and any lock-protected region must perform O(1) work so threads do not stall behind long scans.
  • seat_allocator(n, operations, arguments) constructs SeatAllocator(n), executes each method name listed in operations (such as "claimSeat" with [] in arguments), and returns the list of outputs in call order.

Examples

Example 1

Input:
  n = 4
  operations = ["claimSeat", "claimSeat", "claimSeat", "claimSeat", "claimSeat"]
  arguments = [[], [], [], [], []]

Output:
  [0, 1, 2, 3, -1]

Explanation: The venue holds 4 seats (0, 1, 2, 3). The first four "claimSeat" calls assign 0, 1, 2, and 3 in ascending order. By the fifth call, zero unassigned seats remain, so claimSeat() returns -1.

Example 2

Input:
  n = 5
  operations = ["claimSeat", "claimSeat"]
  arguments = [[], []]

Output:
  [0, 1]

Explanation: Two calls arrive for a 5-seat pool. They receive the two smallest indices (0 and 1), leaving seats 2, 3, and 4 unclaimed.

Constraints

  • 1 <= n <= 10^7
  • 0 <= len(operations) == len(arguments) <= 10^5
  • Each entry in operations is "claimSeat" paired with [] in arguments.
  • SeatAllocator.claimSeat must remain thread-safe under simultaneous multithreaded access while keeping synchronization overhead minimal.

Step-by-step walkthrough

  1. Understand the goal and concurrency rules

    We have n seats numbered 0 through n - 1 (with n up to 10^7). Calling claimSeat() must return the lowest unclaimed seat number, or -1 once every seat is sold. Seats are never released.

    Because many threads may call claimSeat() at the exact same moment, our SeatAllocator class must guarantee: 1. No double-selling: two threads never receive the same seat number. 2. Valid bounds: no call ever returns a seat >= n. 3. Minimal lock contention: if we use a lock, we hold it for the shortest possible work.

    We also implement seat_allocator(n, operations, arguments) so the automated judge can instantiate SeatAllocator(n) and replay a list of "claimSeat" calls.

  2. Why a boolean seat list is too slow

    A first instinct is to create taken = [False] * n and, on every claimSeat() call, acquire a lock, scan from 0 to n - 1 for the first False, flip it to True, and return that index.

    That works on tiny inputs, but fails at scale for three reasons: - Slow scans: claiming seat k scans past k already-taken seats, so selling out the venue takes 0 + 1 + ... + (n - 1) = O(n^2) checks — roughly 5 * 10^13 operations when n = 10^7. - Long lock holds: every other thread sits frozen waiting for the lock while the active thread scans millions of booleans. - Wasted memory: allocating 10^7 booleans up front pays O(n) memory even if only 5 tickets are ever sold.

  3. Key insight: claimed seats always form a prefix

    Why would we ever scan for a gap if gaps cannot form? Because seats are handed out lowest-first and never returned, the claimed seats after k successful calls are always the unbroken prefix 0, 1, ..., k - 1:

    Initial (0 claimed):   [ 0   1   2   3   4 ]
                             ^ next_seat = 0
    
    After 2 claims:        [ X   X   2   3   4 ]
                                     ^ next_seat = 2  (lowest free seat!)
    
    Sold out (5 claims):   [ X   X   X   X   X ]
                                                 ^ next_seat = 5 == n  (return -1)
    

    That means we do not need an array of seats at all! One integer self.next_seat (starting at 0) tells us the exact lowest available seat in O(1) time and O(1) memory.

  4. Why an unprotected counter still has a race condition

    Reducing the state to one integer makes each claim fast, not automatically thread-safe. Checking self.next_seat >= self.n, reading self.next_seat, and adding 1 are separate steps that two threads can interleave (a race condition):

    Suppose n = 8 and next_seat = 7 (the very last seat):
    
    Thread A: checks 7 >= 8 (False)
    Thread B: checks 7 >= 8 (False)          <- B slipped in before A incremented!
    Thread A: reads 7, sets next_seat = 8    -> returns 7
    Thread B: reads 8, sets next_seat = 9    -> returns 8 (INVALID SEAT!)
    
    Or at next_seat = 3:
    Thread A: reads next_seat -> 3
    Thread B: reads next_seat -> 3
    Thread A: writes 3 + 1 = 4               -> returns 3
    Thread B: writes 3 + 1 = 4               -> returns 3 (SOLD TWICE!)
    

    In languages with hardware-backed atomic primitives (such as Java's AtomicInteger.getAndIncrement() or C++'s std::atomic::fetch_add), an atomic fetch-and-add reads the old integer and adds 1 in one uninterruptible CPU step. Python's standard library does not expose an atomic integer, so we wrap those exact lines in a mutex (threading.Lock()), which ensures only one thread enters the block at a time.

  5. Implement SeatAllocator with a minimal critical section

    Inside with self.lock:, we do only three constant-time integer operations: compare self.next_seat >= self.n, copy self.next_seat into claimed_seat, and increment self.next_seat += 1.

    Notice why we check self.next_seat >= self.n before incrementing: once next_seat reaches n, later calls immediately return -1 without pushing next_seat higher and higher.

    class SeatAllocator:
        def __init__(self, n: int):
            # n: total seat count, valid seat numbers are 0 .. n - 1.
            self.n = n
            # next_seat: lowest unclaimed seat index; since seats are never released,
            # claimed seats always form the contiguous prefix 0 .. next_seat - 1.
            self.next_seat = 0
            # lock: mutex ensuring only one thread checks and advances next_seat at a time.
            self.lock = threading.Lock()
    
        def claimSeat(self) -> int:
            # Critical section: bound-check, read, and increment must run as one indivisible step
            # so two threads never claim the same seat or step past n - 1.
            with self.lock:
                if self.next_seat >= self.n:
                    return -1
                claimed_seat = self.next_seat
                self.next_seat += 1
            return claimed_seat
    
  6. Wire up the judge wrapper and trace Example 1

    The judge helper seat_allocator creates SeatAllocator(n), runs each operation in operations, and collects the outputs:

    def seat_allocator(n: int, operations: List[str], arguments: List[List[int]]) -> List[int]:
        # Replay the sequence of allocator method calls and collect each returned seat ID.
        allocator = SeatAllocator(n)
        results: List[int] = []
        for op in operations:
            if op == "claimSeat":
                results.append(allocator.claimSeat())
            else:
                raise ValueError(f"unknown operation: {op}")
        return results
    

    Tracing Example 1 (n = 4, five "claimSeat" calls):

    Call #   next_seat (before)   next_seat >= 4?   Returned   next_seat (after)
    ------   ------------------   ---------------   --------   -----------------
      1              0                  No              0              1
      2              1                  No              1              2
      3              2                  No              2              3
      4              3                  No              3              4
      5              4                  Yes            -1              4
    

    Output: [0, 1, 2, 3, -1]. Under multithreading, self.lock serializes concurrent arrivals into some one-at-a-time order, so the exact same table guarantees 0, 1, 2, and 3 are handed out once each and every later caller receives -1.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import threading
    
    
    class SeatAllocator:
        def __init__(self, n: int):
            # n: total seat count, valid seat numbers are 0 .. n - 1.
            self.n = n
            # next_seat: lowest unclaimed seat index; since seats are never released,
            # claimed seats always form the contiguous prefix 0 .. next_seat - 1.
            self.next_seat = 0
            # lock: mutex ensuring only one thread checks and advances next_seat at a time.
            self.lock = threading.Lock()
    
        def claimSeat(self) -> int:
            # Critical section: bound-check, read, and increment must run as one indivisible step
            # so two threads never claim the same seat or step past n - 1.
            with self.lock:
                if self.next_seat >= self.n:
                    return -1
                claimed_seat = self.next_seat
                self.next_seat += 1
            return claimed_seat
    
    
    def seat_allocator(n: int, operations: List[str], arguments: List[List[int]]) -> List[int]:
        # Replay the sequence of allocator method calls and collect each returned seat ID.
        allocator = SeatAllocator(n)
        results: List[int] = []
        for op in operations:
            if op == "claimSeat":
                results.append(allocator.claimSeat())
            else:
                raise ValueError(f"unknown operation: {op}")
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a deli counter ticket dispenser loaded with a roll of tickets numbered 0 through N - 1. Because customers only pull tickets off the roll and never return them, you do not need a seating chart tracking all N seats individually — the lowest unclaimed seat is always the single number sitting at the front of the roll (next_seat). To prevent two threads from pulling the same number at the same microsecond — a race condition (a concurrency bug where threads interleave steps and read or overwrite stale shared state) — we guard that counter with a mutex (threading.Lock — a mutual-exclusion lock that lets only one thread at a time execute a protected block of code, called a critical section).

Why do other obvious designs fail? Keeping a boolean list [False] * n and scanning from index 0 for the first False under a lock wastes O(n) memory up front and takes O(n) time per claim (O(n^2) across 10^7 seats), stalling every waiting thread while one thread scans millions of taken seats. Conversely, using a bare integer self.next_seat += 1 without synchronization splits "compare < n, read next_seat, write next_seat + 1" across separate steps, allowing two threads to sell the same seat twice or hand out invalid seat n.

Let's trace SeatAllocator(4) from Example 1 if five threads (A, B, C, D, E) invoke claimSeat() concurrently:

Initial state: n = 4, next_seat = 0

1. Thread B acquires lock -> 0 < 4 -> claims 0, sets next_seat = 1, releases lock
2. Thread A acquires lock -> 1 < 4 -> claims 1, sets next_seat = 2, releases lock
3. Thread D acquires lock -> 2 < 4 -> claims 2, sets next_seat = 3, releases lock
4. Thread C acquires lock -> 3 < 4 -> claims 3, sets next_seat = 4, releases lock
5. Thread E acquires lock -> 4 >= 4 -> returns -1, next_seat stays 4, releases lock

Every valid seat (0, 1, 2, 3) is assigned to a single thread, and once sold out, every subsequent caller immediately gets -1.

Complexity

Let n be the number of seats and m be len(operations) in the judge driver.

  • Time: O(1) per __init__ and O(1) per claimSeat() (O(m) total for m operations). Initialization stores two integers and one lock without looping over n, and each claimSeat() executes one lock acquisition, one integer comparison, and at most one addition.
  • Space: O(1) inside SeatAllocator (plus O(m) for the results list returned by seat_allocator). Because claimed seats always form the contiguous prefix 0 .. next_seat - 1, n = 10^7 uses the exact same three fields as n = 4.

Edge cases

  • Single seat (n = 1): First call returns 0; every call after that hits 1 >= 1 and returns -1.
  • Repeated calls after sell-out: self.next_seat stops advancing at n and returns -1 indefinitely without integer growth.
  • Huge n (10^7) with only a few claims: Zero per-seat setup means SeatAllocator(10**7) initializes instantly.
  • Empty operations list: seat_allocator returns [] without touching claimSeat().
  • High thread contention: self.lock serializes concurrent callers so seats 0 .. n - 1 are handed out once each, and within any single thread's sequence of calls, returned seat numbers strictly increase until -1.

Common mistakes

  • Relying on CPython's Global Interpreter Lock (GIL) instead of a real lock: The GIL (an interpreter-level lock in standard CPython that runs one thread's Python bytecode at a time) does not make multi-step statements atomic — thread switches can still happen between bytecode instructions or inside custom comparisons, and free-threaded Python builds disable the GIL completely.
  • Putting if self.next_seat >= self.n outside with self.lock: If two threads both check next_seat < n at n - 1 before taking the lock to increment, the second thread will still increment to n and return out-of-range seat n. (Checking >= n unlocked as a fast-path only to return -1 is safe in languages with atomic reads, provided you still re-check < n after acquiring the lock!)
  • Performing slow I/O, logging, or network calls inside with self.lock: Anything slow inside the critical section serializes all threads behind that slow work; keep only the counter check and increment inside the lock.
  • Allocating [False] * n or list(range(n)) in __init__: Consumes O(n) memory up front and turns a constant-time constructor into millions of allocations for n = 10^7.

Alternative approaches

  • Atomic fetch-and-add (AtomicInteger.getAndIncrement in Java, std::atomic::fetch_add in C++): Uses a single hardware atomic fetch-and-add instruction (a CPU operation that adds 1 to a memory word and returns its previous value without any possibility of interruption) with zero locks; if the old value is >= n, return -1 (using a 64-bit integer so post-sellout increments never overflow).
  • Compare-and-swap (CAS) loop: A compare-and-swap instruction updates a variable from old to new only if its value in memory is still old. Reading cur, returning -1 if cur >= n, and looping until CAS(next_seat, cur, cur + 1) succeeds avoids OS locks while still clamping next_seat at n.

Follow-up questions

  • How would your data structures change if callers could also release previously claimed seats back into the pool? Once seats can be freed, gaps open below next_seat, so a single counter is no longer enough. Keep next_seat as the high-water mark for never-assigned seats alongside a min-heap (heapq — a binary tree stored in an array that pops its smallest element in O(log k) time) holding freed seat IDs, plus a freed_set (hash set) so duplicate releaseSeat(s) calls cannot push the same seat twice: inside with self.lock, claimSeat() pops from the min-heap whenever it is non-empty (every freed seat is guaranteed < next_seat) and otherwise increments next_seat, running in O(log r) time for r currently available freed seats.
  • How does a mutex-guarded counter compare against lock-free atomic primitives (fetch-and-add or compare-and-swap) under heavy multi-core contention and large seat counts? Capacity n itself barely matters because both designs store a single integer (10^7 fits inside 32 bits); the real factor is thread contention (how many CPU cores invoke claimSeat() at once). Under heavy contention, a mutex puts losing threads to sleep in the OS kernel, paying microsecond-scale context switches and stalling everyone if the lock-holding thread gets preempted, whereas a hardware atomic integer (fetch_add or CAS) stays in user space — fetch_add finishes in one non-blocking cache-coherence round trip per thread, while CAS retries in a tight loop on collisions. If hundreds of cores still bottleneck bouncing one cache line, worker threads can claim contiguous blocks of B seats (for example, 64 at a time) from the global counter at the cost of relaxing strict global seat order across active blocks.
  • How could you guarantee strict arrival-order (FIFO) fairness when thousands of threads compete for seats simultaneously? Standard OS mutexes (threading.Lock) wake waiting threads in throughput-friendly order rather than arrival order, so an unlucky thread can be overtaken repeatedly. To enforce FIFO (first-in, first-out, serving callers strictly in arrival order), use a ticket lock (each arriving thread atomically grabs an incrementing ticket number and waits until now_serving == ticket—or directly takes seat ticket if ticket < n!) or place incoming requests into a thread-safe FIFO queue (queue.Queue) drained by a dedicated O(1) allocator worker; in distributed ticketing services, pair this with an upstream virtual waiting room that issues monotonic sequence tokens on entry.

Follow-up questions

Similar questions

More Target interview questions

All 2 Target questions →