DSA Heaps

The Number of the Smallest Unoccupied Chair

Friends arrive and leave at intervals — return which chair the target friend sits on, using two heaps.

Medium
Time O(n log n) Space O(n)
LeetCode
6 min read
heaps

Problem#

times[i] = [arrive, leave] for friend i. Each friend takes the smallest-numbered free chair on arrival and frees it on leave. Return the chair the target friend sits on.

Examples#

  • times = [[1,4],[2,3],[4,6]], targetFriend = 11

Constraints#

  • 2 <= times.length <= 10^4.

Approach#

Sort friends by arrival, remembering original indices. Two heaps: free (chair numbers, min-heap) and busy ((leave, chair), min-heap by leave). For each friend in order: free up expired chairs into free; take the smallest free chair. If that’s the target, return.

Solution#

Smallest Unoccupied Chair
class Solution {
public:
int smallestChair(vector<vector<int>>& times, int targetFriend) {
int n = times.size();
vector<tuple<int,int,int>> arrs(n);
for (int i = 0; i < n; ++i) arrs[i] = {times[i][0], times[i][1], i};
sort(arrs.begin(), arrs.end());
priority_queue<int, vector<int>, greater<int>> freeChairs;
for (int i = 0; i < n; ++i) freeChairs.push(i);
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<>> busy;
for (auto& [arr, lea, idx] : arrs) {
while (!busy.empty() && busy.top().first <= arr) {
freeChairs.push(busy.top().second);
busy.pop();
}
int chair = freeChairs.top(); freeChairs.pop();
if (idx == targetFriend) return chair;
busy.push({lea, chair});
}
return -1;
}
};

Editorial#

Same two-heap pattern as Meeting Rooms III. Sorting by arrival preserves the simulation order; the free-chair heap orders by number, and the busy heap orders by leave time so expirations process in order.

Complexity#

  • Time: O(n log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.