Talentd
FleetCode
Make and follow sheets.Sign in

Seat Reservation Manager solution and explanation

MediumDesignHeap (Priority Queue)6 min read67.1% acceptanceUpdated 9 Apr 2026
Seat Reservation Manager - Leetcode 1845 - PythonNeetCode · 7:42 · 9K viewsWatch on YouTube
9 more videos on this problem
  1. Seat Reservation Manager - Leetcode 1845 - PythonNeetCode · 7:42 · 9K views
  2. Seat Reservation Manager | 3 Ways | Intuition | META | Leetcode - 1845codestorywithMIK · 24:05 · 4K views
  3. Seat Reservation Manager | LeetCode 1845 | Design | DropBox | TreeSet | MinHeapNaresh Gupta · 8:16 · 1K views
  4. Daily Leetcode #1315: Nov 06, 2023 - 1845. Seat Reservation ManagerProgramming Live with Larry · 5:17 · 352 views
  5. 1845. Seat Reservation Manager | Leetcode Problem of the dayRuntime Error · 10:00 · 329 views
  6. Seat Reservation Manager (Leetcode 1845)Coding Interviews · 28:47 · 235 views
  7. 1845. Seat Reservation Manager (Leetcode Medium)Programming Live with Larry · 4:00 · 230 views
  8. Solving LeetCode 1845 Seat Reservation Manager | Meta / Facebook Interview Question | Min HeapCode Harmony · 11:55 · 212 views
  9. 1845. Seat Reservation Manager - LeetCode Question solutionAlgorithmX by Srishti · 10:01 · 146 views
  10. 1845. Seat Reservation Manager || LeetCode Daily || C++ solution + intuitionPriyanshi Porwal · 12:21 · 133 views

The problem

Design a system that manages the reservation state of n seats that are numbered from 1 to n.

Implement the SeatManager class:

  • SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n. All seats are initially available.
  • int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number.
  • void unreserve(int seatNumber) Unreserves the seat with the given seatNumber.

Example 1:

Input
["SeatManager", "reserve", "reserve", "unreserve", "reserve", "reserve", "reserve", "reserve", "unreserve"]
[[5], [], [], [2], [], [], [], [], [5]]
Output
[null, 1, 2, null, 2, 3, 4, 5, null]

Explanation
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve();    // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve();    // The available seats are [2,3,4,5], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5].
seatManager.reserve();    // The available seats are [2,3,4,5], so return the lowest of them, which is 2.
seatManager.reserve();    // The available seats are [3,4,5], so return the lowest of them, which is 3.
seatManager.reserve();    // The available seats are [4,5], so return the lowest of them, which is 4.
seatManager.reserve();    // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5].

Constraints:

  • 1 <= n <= 105
  • 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 105 calls in total will be made to reserve and unreserve.

Approach overview

Problem Overview: You need to design a seat reservation system that always assigns the smallest available seat number. Two operations exist: reserve() returns the lowest-numbered free seat, and unreserve(seatNumber) makes a seat available again. The challenge is maintaining the smallest free seat efficiently as seats are reserved and returned.

Approach 1: Min-Heap for Available Seats (O(log n) per operation)

The most common solution uses a min-heap (priority queue) to track all currently available seat numbers. Initially, push all seats from 1 to n into the heap. When reserve() is called, remove the smallest element using heappop() or poll(), which guarantees the lowest-numbered seat. When unreserve(seatNumber) is called, push that seat number back into the heap so it becomes available again. Each heap push or pop costs O(log n) time and the heap stores up to O(n) elements. This approach works well because heaps are optimized for repeatedly extracting the smallest value.

Approach 2: TreeSet (Sorted Set) to Track Free Seats (O(log n) per operation)

A TreeSet or other balanced binary search tree can maintain seat numbers in sorted order. Insert all seat numbers from 1 to n into the set during initialization. The reserve() operation retrieves and removes the smallest element using first() and remove(). When unreserve(seatNumber) is called, insert that seat number back into the set. Because a TreeSet is backed by a self-balancing BST, both insertion and deletion take O(log n) time while maintaining sorted order. Space complexity is O(n). This method is clean and idiomatic in languages like Java or C# where sorted sets are built-in.

Both approaches fall under the design category because you are implementing a data structure with defined operations and performance guarantees. The key observation is that the smallest available seat must always be accessible quickly. Using either a heap or a balanced ordered set ensures that retrieving the minimum value remains efficient even as seats are returned to the pool.

Recommended for interviews: The min-heap solution is usually expected. It directly models the requirement of always retrieving the smallest available seat and keeps the implementation simple. The TreeSet solution demonstrates familiarity with ordered sets and balanced trees, which is useful in languages with strong standard libraries. Showing both approaches signals strong understanding of priority queues and ordered data structures.

Approach 1: Using a Min-Heap to Manage Seats

In this approach, we use a min-heap (priority queue) to efficiently manage and retrieve the smallest numbered unreserved seat.

  • When we initialize the SeatManager, we populate the heap with all seat numbers from 1 to n.
  • For the reserve method, we simply extract the minimum element from the heap, which is the smallest numbered available seat.
  • To unreserve a seat, we add back the seat number to the heap, maintaining the heap properties.
import heapq

class SeatManager:
    def __init__(self, n: int):
        self.available_seats = list(range(1, n + 1))
        heapq.heapify(self.available_seats)

    def reserve(self) -> int:
        return heapq.heappop(self.available_seats)

    def unreserve(self, seatNumber: int) -> None:
        heapq.heappush(self.available_seats, seatNumber)
import java.util.PriorityQueue;

class SeatManager {
    private PriorityQueue<Integer> availableSeats;

    public SeatManager(int n) {
        availableSeats = new PriorityQueue<>();
        for (int i = 1; i <= n; i++) {
            availableSeats.add(i);
        }
    }

    public int reserve() {
        return availableSeats.poll();
    }

    public void unreserve(int seatNumber) {
        availableSeats.add(seatNumber);
    }
}

The Python solution uses the built-in heapq module to manage a min-heap representing the available seats. Initially, all seats are added to the heap. The reserve method pops the smallest item, while unreserve pushes a seat number back into the heap.

Complexity

Time Complexity: O(log n) for both reserve and unreserve operations. We have to push and pop elements into/from a heap which takes logarithmic time.

Space Complexity: O(n) because of the storage required for the heap.

Try this approach in the editor

Approach 2: Using a TreeSet (Sorted Set) to Manage Seats

Here, we use a data structure that maintains elements in sorted order, such as a TreeSet in Java and C# which keeps the seats sorted automatically.

  • Seats are stored in a sorted set, so we can easily access the smallest available seat.
  • reserve operation fetches and removes the first (smallest) element from the set.
  • In the unreserve method, we simply add back the seat number to the set.
import java.util.TreeSet;

class SeatManager {
    private TreeSet<Integer> availableSeats;

    public SeatManager(int n) {
        availableSeats = new TreeSet<>();
        for (int i = 1; i <= n; i++) {
            availableSeats.add(i);
        }
    }

    public int reserve() {
        int seatNumber = availableSeats.first();
        availableSeats.remove(seatNumber);
        return seatNumber;
    }

    public void unreserve(int seatNumber) {
        availableSeats.add(seatNumber);
    }
}
using System.Collections.Generic;

public class SeatManager {
    private SortedSet<int> availableSeats;

    public SeatManager(int n) {
        availableSeats = new SortedSet<int>();
        for (int i = 1; i <= n; i++) {
            availableSeats.Add(i);
        }
    }

    public int Reserve() {
        int seatNumber = availableSeats.Min;
        availableSeats.Remove(seatNumber);
        return seatNumber;
    }

    public void Unreserve(int seatNumber) {
        availableSeats.Add(seatNumber);
    }
}

The Java solution with TreeSet maintains a sorted set of available seats. The reserve method retrieves and removes the smallest element, while unreserve re-adds a seat number.

Complexity

Time Complexity: O(log n) for both reserve and unreserve operations because TreeSet operations like add, remove, and first take logarithmic time.

Space Complexity: O(n), as we store up to n seat numbers.

Try this approach in the editor

Approach 3: Priority Queue (Min-Heap)

We define a priority queue (min-heap) q to store all the available seat numbers. Initially, we add all seat numbers from 1 to n into q.

When calling the reserve method, we pop the top element from q, which is the smallest available seat number.

When calling the unreserve method, we add the seat number back into q.

In terms of time complexity, the initialization time complexity is O(n) or O(n times log n), and the time complexity of the reserve and unreserve methods is both O(log n). The space complexity is O(n).

class SeatManager {
public:
    SeatManager(int n) {
        for (int i = 1; i <= n; ++i) {
            q.push(i);
        }
    }

    int reserve() {
        int seat = q.top();
        q.pop();
        return seat;
    }

    void unreserve(int seatNumber) {
        q.push(seatNumber);
    }

private:
    priority_queue<int, vector<int>, greater<int>> q;
};

/**
 * Your SeatManager object will be instantiated and called as such:
 * SeatManager* obj = new SeatManager(n);
 * int param_1 = obj->reserve();
 * obj->unreserve(seatNumber);
 */
class SeatManager {
    private q = new MinPriorityQueue<number>();
    constructor(n: number) {
        for (let i = 1; i <= n; i++) {
            this.q.enqueue(i);
        }
    }

    reserve(): number {
        return this.q.dequeue();
    }

    unreserve(seatNumber: number): void {
        this.q.enqueue(seatNumber);
    }
}

/**
 * Your SeatManager object will be instantiated and called as such:
 * var obj = new SeatManager(n)
 * var param_1 = obj.reserve()
 * obj.unreserve(seatNumber)
 */
type SeatManager struct {
	q hp
}

func Constructor(n int) SeatManager {
	q := hp{}
	for i := 1; i <= n; i++ {
		heap.Push(&q, i)
	}
	return SeatManager{q}
}

func (this *SeatManager) Reserve() int {
	return heap.Pop(&this.q).(int)
}

func (this *SeatManager) Unreserve(seatNumber int) {
	heap.Push(&this.q, seatNumber)
}

type hp struct{ sort.IntSlice }

func (h hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] }
func (h *hp) Push(v any)        { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
	a := h.IntSlice
	v := a[len(a)-1]
	h.IntSlice = a[:len(a)-1]
	return v
}

/**
 * Your SeatManager object will be instantiated and called as such:
 * obj := Constructor(n);
 * param_1 := obj.Reserve();
 * obj.Unreserve(seatNumber);
 */
Try this approach in the editor

Complexity comparison

ApproachComplexity
Using a Min-Heap to Manage Seats

Time Complexity: O(log n) for both reserve and unreserve operations. We have to push and pop elements into/from a heap which takes logarithmic time.

Space Complexity: O(n) because of the storage required for the heap.

Using a TreeSet (Sorted Set) to Manage Seats

Time Complexity: O(log n) for both reserve and unreserve operations because TreeSet operations like add, remove, and first take logarithmic time.

Space Complexity: O(n), as we store up to n seat numbers.

Priority Queue (Min-Heap)–

Complexity analysis

ApproachTimeSpaceWhen to Use
Min-Heap (Priority Queue)O(log n) per reserve/unreserveO(n)Best general solution when you need constant access to the smallest available seat
TreeSet / Sorted SetO(log n) per operationO(n)Ideal in languages with built-in ordered sets like Java or C#

Frequently asked questions

Is Seat Reservation Manager easy or hard?

Seat Reservation Manager is rated Medium difficulty. The logic is straightforward once you recognize that the smallest available seat must be tracked dynamically using a priority queue or ordered set.

Seat Reservation Manager Python/Java solution

Python solutions typically use the heapq module to implement the priority queue. Java implementations often use PriorityQueue or TreeSet depending on the approach. Both maintain sorted seat availability and support O(log n) updates.

How to solve Seat Reservation Manager in O(n)?

Initialization takes O(n) time by inserting seat numbers from 1 to n into a data structure like a min-heap or TreeSet. After initialization, each reserve() and unreserve() operation runs in O(log n). The overall design ensures efficient dynamic seat allocation.

What is the best approach for Seat Reservation Manager?

The best approach uses a min-heap (priority queue) to store all available seat numbers. The reserve() operation pops the smallest seat in O(log n) time, while unreserve(seatNumber) pushes the seat back into the heap in O(log n). This guarantees that the lowest-numbered seat is always returned efficiently.

Is Seat Reservation Manager asked at Google/Amazon/Meta?

Design-style data structure problems like Seat Reservation Manager appear in interviews at large tech companies including Amazon, Google, and Meta. They test your ability to design efficient APIs and choose the correct data structure such as heaps or balanced trees.

What data structure is used in Seat Reservation Manager?

The most common data structure is a min-heap (priority queue) that always exposes the smallest available seat. Another valid option is a TreeSet or ordered set implemented with a balanced binary search tree.

What is the time complexity of Seat Reservation Manager?

Both the Min-Heap and TreeSet solutions run each operation in O(log n) time. Reserving a seat requires extracting the smallest element, and unreserving requires inserting it back. Space complexity is O(n) because all available seat numbers must be stored.

Comments

Now write it yourselfClose this page and solve Seat Reservation Manager in the editor, without looking.
Practise Seat Reservation Manager