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 managingnseats (0ton - 1).claimSeat()atomically assigns and returns the smallest unassigned seat index, or-1when capacity is exhausted. Concurrent callers must never receive duplicate indices or values outside0 .. n - 1, and any lock-protected region must performO(1)work so threads do not stall behind long scans.seat_allocator(n, operations, arguments)constructsSeatAllocator(n), executes each method name listed inoperations(such as"claimSeat"with[]inarguments), 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^70 <= len(operations) == len(arguments) <= 10^5- Each entry in
operationsis"claimSeat"paired with[]inarguments. SeatAllocator.claimSeatmust remain thread-safe under simultaneous multithreaded access while keeping synchronization overhead minimal.
Step-by-step walkthrough
Understand the goal and concurrency rules
We have
nseats numbered0throughn - 1(withnup to10^7). CallingclaimSeat()must return the lowest unclaimed seat number, or-1once every seat is sold. Seats are never released.Because many threads may call
claimSeat()at the exact same moment, ourSeatAllocatorclass 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 instantiateSeatAllocator(n)and replay a list of"claimSeat"calls.Why a boolean seat list is too slow
A first instinct is to create
taken = [False] * nand, on everyclaimSeat()call, acquire a lock, scan from0ton - 1for the firstFalse, flip it toTrue, and return that index.That works on tiny inputs, but fails at scale for three reasons: - Slow scans: claiming seat
kscans pastkalready-taken seats, so selling out the venue takes0 + 1 + ... + (n - 1) = O(n^2)checks — roughly5 * 10^13operations whenn = 10^7. - Long lock holds: every other thread sits frozen waiting for the lock while the active thread scans millions of booleans. - Wasted memory: allocating10^7booleans up front paysO(n)memory even if only5tickets are ever sold.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
ksuccessful calls are always the unbroken prefix0, 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 at0) tells us the exact lowest available seat inO(1)time andO(1)memory.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, readingself.next_seat, and adding1are 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++'sstd::atomic::fetch_add), an atomic fetch-and-add reads the old integer and adds1in 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.Implement SeatAllocator with a minimal critical section
Inside
with self.lock:, we do only three constant-time integer operations: compareself.next_seat >= self.n, copyself.next_seatintoclaimed_seat, and incrementself.next_seat += 1.Notice why we check
self.next_seat >= self.nbefore incrementing: oncenext_seatreachesn, later calls immediately return-1without pushingnext_seathigher 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_seatWire up the judge wrapper and trace Example 1
The judge helper
seat_allocatorcreatesSeatAllocator(n), runs each operation inoperations, 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 resultsTracing 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 4Output:
[0, 1, 2, 3, -1]. Under multithreading,self.lockserializes concurrent arrivals into some one-at-a-time order, so the exact same table guarantees0,1,2, and3are handed out once each and every later caller receives-1.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__andO(1)perclaimSeat()(O(m)total formoperations). Initialization stores two integers and one lock without looping overn, and eachclaimSeat()executes one lock acquisition, one integer comparison, and at most one addition. - Space:
O(1)insideSeatAllocator(plusO(m)for theresultslist returned byseat_allocator). Because claimed seats always form the contiguous prefix0 .. next_seat - 1,n = 10^7uses the exact same three fields asn = 4.
Edge cases
- Single seat (
n = 1): First call returns0; every call after that hits1 >= 1and returns-1. - Repeated calls after sell-out:
self.next_seatstops advancing atnand returns-1indefinitely without integer growth. - Huge
n(10^7) with only a few claims: Zero per-seat setup meansSeatAllocator(10**7)initializes instantly. - Empty
operationslist:seat_allocatorreturns[]without touchingclaimSeat(). - High thread contention:
self.lockserializes concurrent callers so seats0 .. n - 1are 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.noutsidewith self.lock: If two threads both checknext_seat < natn - 1before taking the lock to increment, the second thread will still increment tonand return out-of-range seatn. (Checking>= nunlocked as a fast-path only to return-1is safe in languages with atomic reads, provided you still re-check< nafter 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] * norlist(range(n))in__init__: ConsumesO(n)memory up front and turns a constant-time constructor into millions of allocations forn = 10^7.
Alternative approaches
- Atomic fetch-and-add (
AtomicInteger.getAndIncrementin Java,std::atomic::fetch_addin C++): Uses a single hardware atomic fetch-and-add instruction (a CPU operation that adds1to 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
oldtonewonly if its value in memory is stillold. Readingcur, returning-1ifcur >= n, and looping untilCAS(next_seat, cur, cur + 1)succeeds avoids OS locks while still clampingnext_seatatn.
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. Keepnext_seatas 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 inO(log k)time) holding freed seat IDs, plus afreed_set(hash set) so duplicatereleaseSeat(s)calls cannot push the same seat twice: insidewith self.lock,claimSeat()pops from the min-heap whenever it is non-empty (every freed seat is guaranteed< next_seat) and otherwise incrementsnext_seat, running inO(log r)time forrcurrently 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
nitself barely matters because both designs store a single integer (10^7fits inside 32 bits); the real factor is thread contention (how many CPU cores invokeclaimSeat()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_addor CAS) stays in user space —fetch_addfinishes 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 ofBseats (for example,64at 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 incrementingticketnumber and waits untilnow_serving == ticket—or directly takes seatticketifticket < n!) or place incoming requests into a thread-safe FIFO queue (queue.Queue) drained by a dedicatedO(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
- How would your data structures change if callers could also release previously claimed seats back into the pool?
- 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?
- How could you guarantee strict arrival-order (FIFO) fairness when thousands of threads compete for seats simultaneously?
Similar questions
- Nearest String Match Under Edit Distance
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager