The Number of the Smallest Unoccupied Chair — LeetCode 1942 Python Solution
MediumArrayHash TableHeap (Priority Queue)
- Problem
- #1942
- Pattern
- Heap / Priority Queue
- Reading time
- 3 min
- Source
- leetcode.com
The problem
There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity.
Example
- Input
- times = [[1,4],[2,3],[4,6]], targetFriend = 1
- Output
- 1
- Explanation
- - Friend 0 arrives at time 1 and sits on chair 0.
Python solution
Python
class Solution:
def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:
n = len(times)
for i in range(n):
times[i].append(i)
times.sort()
idle = list(range(n))
heapify(idle)
busy = []
for arrival, leaving, i in times:
while busy and busy[0][0] <= arrival:
heappush(idle, heappop(busy)[1])
j = heappop(idle)
if i == targetFriend:
return j
heappush(busy, (leaving, j))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1942. The Number of the Smallest Unoccupied Chair is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1942. The Number of the Smallest Unoccupied Chair?
- LeetCode 1942. The Number of the Smallest Unoccupied Chair is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1942. The Number of the Smallest Unoccupied Chair?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 1942. The Number of the Smallest Unoccupied Chair?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1942. The Number of the Smallest Unoccupied Chair cover?
- LeetCode 1942. The Number of the Smallest Unoccupied Chair is tagged Array, Hash Table and Heap (Priority Queue) on LeetCode.