Seat Reservation Manager
Problem Statement
A hall has n seats numbered from 1 to n. Build a class SeatManager that hands out seats.
SeatManager(int n)starts with allnseats free.int reserve()takes the smallest-numbered free seat, marks it taken, and returns its number.void unreserve(int seatNumber)makes a taken seat free again.
The number n, then a series of reserve() and unreserve(seatNumber) calls.
For each reserve() call, the seat number it gave out. unreserve returns nothing.
Seats 1 and 2 go out first. Seat 2 is given back, so the next reserve takes 2 again, because it is the smallest free seat. Then 3, 4 and 5 go out in order. Giving back 5 leaves it free.
After unreserve(3) and unreserve(1), seats 1 and 3 are free. The smallest one, 1, comes out first, even though seat 3 was given back earlier.
- • 1 ≤ n ≤ 10^5
- • 1 ≤ seatNumber ≤ n
- • For each call to reserve, it is guaranteed that there will be at least one unreserved seat
- • For each call to unreserve, it is guaranteed that seatNumber will be reserved
- • At most 10^5 calls in total will be made to reserve and unreserve
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Boolean array of taken seats; reserve scans from seat 1 for the first free one
Put all n seats in a min-heap at the start; reserve pops the top, unreserve pushes back
A counter covers the never-used seats; a min-heap holds only the seats that were given back
Keep taken[s] for every seat. reserve scans from seat 1 and takes the first seat whose flag is false. unreserve clears that seat's flag.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Heap — Top K translate into production architectures and low-level memory mechanics.