#1942
The Number of the Smallest Unoccupied Chair
MediumArrayHash TableHeap (Priority Queue)Hash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
We can use a priority queue (min-heap) to efficiently manage the chairs. By keeping track of the next available chair and the leaving times, we can quickly determine which chair is free when a friend arrives.
⚙️
Algorithm
3 steps- 1Step 1: Sort the times array by arrival time.
- 2Step 2: Initialize a priority queue to manage available chairs and a list to track occupied chairs.
- 3Step 3: For each friend, check the priority queue for available chairs and update it based on leaving times.
solution.py18 lines
1# Full working Python code
2import heapq
3
4def smallestChair(times, targetFriend):
5 times.sort() # Sort by arrival time
6 available_chairs = [] # Min-heap for available chairs
7 occupied = [] # List to keep track of occupied chairs
8 for i in range(len(times)):
9 arrival, leaving = times[i]
10 # Free chairs that have been left
11 while occupied and occupied[0][0] <= arrival:
12 heapq.heappush(available_chairs, occupied.pop(0)[1])
13 # Get the smallest available chair
14 chair_num = heapq.heappop(available_chairs) if available_chairs else len(occupied)
15 occupied.append((leaving, chair_num)) # Mark chair as occupied
16 if i == targetFriend:
17 return chair_num
18 return -1ℹ
Complexity note: The time complexity is O(n log n) due to sorting the arrival times and managing the priority queue, while the space complexity is O(n) for storing occupied chairs.
- 1Use a priority queue to efficiently manage available chairs.
- 2Sorting the arrival times is crucial for correct chair allocation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.