#1942
Medium Algorithms The number of the smallest unoccupied chair
Array Hash Table Heap (Priority Queue)
60.4% acceptance
Feb 25, 2026
1449
78
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. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number.
For example, if chairs 0, 1, and 5 are occupied when a friend comes, they will sit on chair number 2.
When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair.
You are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi], indicating the arrival and leaving times of the ith friend respectively, and an integer targetFriend. All arrival times are distinct.
Return the chair number that the friend numbered targetFriend will sit on.
Solution
Rust
Time O(n²)
Space O(n)
use std::collections::BinaryHeap;
use std::cmp::Reverse;
impl Solution {
pub fn smallest_chair(times: Vec<Vec<i32>>, target_friend: i32) -> i32 {
let n = times.len();
let mut order: Vec<usize> = (0..n).collect();
order.sort_by_key(|&i| times[i][0]);
let mut available: BinaryHeap<Reverse<i32>> = (0..n as i32).map(Reverse).collect();
let mut leaving: BinaryHeap<Reverse<(i32, i32)>> = BinaryHeap::new(); // (leave_time, chair)
for &i in &order {
let arrive = times[i][0];
let leave = times[i][1];
// Free up chairs from friends who have left
while let Some(&Reverse((lt, chair))) = leaving.peek() {
if lt <= arrive {
leaving.pop();
available.push(Reverse(chair));
} else {
break;
}
}
let Reverse(chair) = available.pop().unwrap();
if i == target_friend as usize {
return chair;
}
leaving.push(Reverse((leave, chair)));
}
-1
}
}