Talentd
FleetCode
Make and follow sheets.Sign in

The Number of the Smallest Unoccupied Chair solution and explanation

MediumArrayHash TableHeap (Priority Queue)7 min read60.3% acceptanceUpdated 9 Apr 2026
The Number of the Smallest Unoccupied Chair - Leetcode 1942 - PythonNeetCodeIO · 15:07 · 12K viewsWatch on YouTube
9 more videos on this problem
  1. The Number of the Smallest Unoccupied Chair - Leetcode 1942 - PythonNeetCodeIO · 15:07 · 12K views
  2. The Number of the Smallest Unoccupied Chair | Brute Force | Optimal |Leetcode 1942 |codestorywithMIKcodestorywithMIK · 32:23 · 11K views
  3. 1942. The Number of the Smallest Unoccupied Chair | Leetcode Daily Challenge | DSA | JavaShashCode · 15:51 · 4K views
  4. LeetCode 1942. The Number of the Smallest Unoccupied Chair O(n2) | 🏆 Biweekly Contest 57 | ExplainedCherry Coding [IIT-G] · 12:53 · 3K views
  5. LeetCode 1942. The Number of the Smallest Unoccupied ChairHappy Coding · 11:38 · 2K views
  6. The Number of the Smallest Unoccupied Chair | Leetcode 1942Techdose · 19:43 · 1K views
  7. 1942. The Number of the Smallest Unoccupied Chair (Leetcode Medium)Programming Live with Larry · 10:23 · 845 views
  8. Daily Leetcode #1655: Oct 11, 2024 - 1942. The Number of the Smallest Unoccupied ChairProgramming Live with Larry · 16:00 · 515 views
  9. The Number of the Smallest Unoccupied Chair | Leetcode 1942 | Priority Queue | Java| Developer CoderDeveloper Coder · 23:53 · 472 views
  10. The Number of the Smallest Unoccupied Chair | Leetcode 1942 | must do Priority Queue DSA questionCode Thoughts · 15:19 · 351 views

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. 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.

Example 1:

Input: times = [[1,4],[2,3],[4,6]], targetFriend = 1
Output: 1
Explanation: 
- Friend 0 arrives at time 1 and sits on chair 0.
- Friend 1 arrives at time 2 and sits on chair 1.
- Friend 1 leaves at time 3 and chair 1 becomes empty.
- Friend 0 leaves at time 4 and chair 0 becomes empty.
- Friend 2 arrives at time 4 and sits on chair 0.
Since friend 1 sat on chair 1, we return 1.

Example 2:

Input: times = [[3,10],[1,5],[2,6]], targetFriend = 0
Output: 2
Explanation: 
- Friend 1 arrives at time 1 and sits on chair 0.
- Friend 2 arrives at time 2 and sits on chair 1.
- Friend 0 arrives at time 3 and sits on chair 2.
- Friend 1 leaves at time 5 and chair 0 becomes empty.
- Friend 2 leaves at time 6 and chair 1 becomes empty.
- Friend 0 leaves at time 10 and chair 2 becomes empty.
Since friend 0 sat on chair 2, we return 2.

Constraints:

  • n == times.length
  • 2 <= n <= 104
  • times[i].length == 2
  • 1 <= arrivali < leavingi <= 105
  • 0 <= targetFriend <= n - 1
  • Each arrivali time is distinct.

Approach overview

Problem Overview: Friends arrive and leave at different times, and each one takes the smallest numbered unoccupied chair when they arrive. When a friend leaves, their chair becomes available again. Given the arrival/leave schedule and a target friend index, you need to determine which chair that friend sits on.

Approach 1: Min-Heap Simulation (O(n log n) time, O(n) space)

This approach models the process exactly as it happens using two heap (priority queue) structures. First, sort all friends by arrival time so events happen in chronological order. Maintain one min-heap for currently occupied chairs keyed by leaving time, and another min-heap that stores available chair numbers. When a friend arrives, repeatedly pop from the occupied heap if their leave time is less than or equal to the current arrival time, pushing those chair numbers back into the free heap. The arriving friend takes the smallest available chair from the free heap. If the arriving friend is the target friend, return that chair number immediately.

The key insight: you never need to simulate all chairs explicitly. The free heap always provides the smallest available chair in O(log n), while the occupied heap quickly releases chairs when friends leave. This solution fits naturally with array processing and event simulation.

Approach 2: Event Scheduling with Ordered Sets (O(n log n) time, O(n) space)

This approach treats arrivals and departures as ordered events and uses a balanced set structure to manage available chairs. Sort friends by arrival time. Maintain a set containing all currently free chair numbers and a structure mapping leave times to the chair occupied by that friend. As you iterate through arrivals, release chairs for all friends whose leave time has passed and reinsert those chair numbers into the set. The arriving friend always picks the smallest element from the set.

The ordered set guarantees that retrieving the smallest free chair takes O(log n). Tracking departures ensures chairs are recycled efficiently. This method often appears in C++ or Java implementations where ordered sets or tree structures are convenient. The scheduling idea closely resembles problems involving hash table lookups combined with sorted events.

Recommended for interviews: The min-heap simulation is the expected solution. It demonstrates understanding of event ordering, priority queues, and resource allocation problems. Explaining the simulation clearly shows strong problem modeling skills, while the heap operations keep the runtime optimal at O(n log n).

Approach 1: Min-Heap Approach

The problem can be efficiently solved by using a min-heap (priority queue) to keep track of the smallest available chair. When a friend arrives, we assign them the smallest chair, and when they leave, their chair is added back to the pool of available chairs. This ensures that friends always get the smallest possible available chair.

We start by sorting all events by time. As we process each event, we use the heap to efficiently manage the available chairs.

import heapq

def smallestChair(times, targetFriend):
    events = []
    for i, (arr, leave) in enumerate(times):
        events.append((arr, i, 'arrive'))
        events.append((leave, i, 'leave'))
    events.sort()
    
    available_chairs = []  # Min-heap for available chair numbers
    occupied_map = {}  # Maps friends to chairs
    current_chair = 0
    
    for time, friend, event_type in events:
        if event_type == 'arrive':
            if not available_chairs:
                chair = current_chair
                current_chair += 1
            else:
                chair = heapq.heappop(available_chairs)
            
            occupied_map[friend] = chair
            
            if friend == targetFriend:
                return chair
        else:  # event_type == 'leave'
            heapq.heappush(available_chairs, occupied_map[friend])
function smallestChair(times, targetFriend) {
    let events = [];
    times.forEach(([arrival, leave], index) => {
        events.push({ time: arrival, index, type: 'arrive' });
        events.push({ time: leave, index, type: 'leave' });
    });
    events.sort((a, b) => a.time - b.time || (a.type === 'leave' ? -1 : 1));

    let availableChairs = new MinPriorityQueue();
    let occupiedChairs = new Map();
    let currentChair = 0;

    for (const { time, index, type } of events) {
        if (type === 'arrive') {
            let chair = availableChairs.isEmpty() ? currentChair++ : availableChairs.dequeue().element;
            occupiedChairs.set(index, chair);

            if (index === targetFriend) {
                return chair;
            }
        } else {
            availableChairs.enqueue(occupiedChairs.get(index));
        }
    }
}

This Python function uses two main structures: a list of events that are sorted by time, and a min-heap to keep track of the smallest available chairs. We iterate through each event, either assigning an available chair to an arriving friend or freeing up a chair when a friend leaves. This method works because the heap operations are logarithmic, keeping the solution efficient.

Complexity

Time Complexity: O(n log n), where n is the number of friends (and thus events). This is due to sorting the events and using heap operations.
Space Complexity: O(n) for storing event data and the heap.

Try this approach in the editor

Approach 2: Event Scheduling with Sets

This approach involves handling chair availability using a sorted list (or equivalent structure) to manage the sequence of chairs efficiently. We simulate arrival and departure events by updating the list and assigning chairs accordingly. While slightly less efficient than a heap in handling dynamic minimum queries, it offers an alternative perspective by focusing on set management operations.

import java.util.*;

class Solution {
    public int smallestChair(int[][] times, int targetFriend) {
        List<int[]> events = new ArrayList<>();
        for (int i = 0; i < times.length; i++) {
            events.add(new int[]{times[i][0], i, 1});  // 1 for arrival
            events.add(new int[]{times[i][1], i, -1}); // -1 for departure
        }
        events.sort((a, b) -> a[0] == b[0] ? Integer.compare(a[2], b[2]) : Integer.compare(a[0], b[0]));

        TreeSet<Integer> availableChairs = new TreeSet<>();
        Map<Integer, Integer> friendToChair = new HashMap<>();
        int nextChair = 0;

        for (int[] event : events) {
            if (event[2] == 1) {  // Arrival
                int chair;
                if (!availableChairs.isEmpty()) {
                    chair = availableChairs.pollFirst();
                } else {
                    chair = nextChair++;
                }
                friendToChair.put(event[1], chair);
                if (event[1] == targetFriend) {
                    return chair;
                }
            } else {  // Departure
                availableChairs.add(friendToChair.get(event[1]));
            }
        }
        return -1;
    }
}
#include <vector>
#include <algorithm>
#include <set>
using namespace std;

int smallestChair(vector<vector<int>>& times, int targetFriend) {
    vector<pair<int, int>> events;
    for (int i = 0; i < times.size(); ++i) {
        events.emplace_back(times[i][0], i);
        events.emplace_back(times[i][1], -i);
    }
    sort(events.begin(), events.end());

    set<int> available_chairs;
    vector<int> friend_to_chair(times.size(), -1);
    int next_chair = 0;

    for (const auto& event : events) {
        int time = event.first;
        int index = event.second;

        if (index >= 0) {  // Arrival event
            int chairNumber;
            if (!available_chairs.empty()) {
                chairNumber = *available_chairs.begin();
                available_chairs.erase(available_chairs.begin());
            } else {
                chairNumber = next_chair++;
            }
            friend_to_chair[index] = chairNumber;

            if (index == targetFriend)
                return chairNumber;

        } else {  // Departure event
            int leavingFriend = -index;
            available_chairs.insert(friend_to_chair[leavingFriend]);
        }
    }
    return -1;
}

This Java approach is quite similar to the C++ implementation, using a TreeSet to manage the list of unoccupied chairs, ensuring that we always assign the smallest available chair when a friend arrives. A map tracks which chair each friend is using.

Complexity

Time Complexity: O(n log n) because of sorting events and TreeSet operations.
Space Complexity: O(n) to maintain maps and sets for event and chair management.

Try this approach in the editor

Approach 3: Priority Queue (Min-Heap)

First, we create a tuple for each friend consisting of their arrival time, leaving time, and index, then sort these tuples by arrival time.

We use a min-heap idle to store the currently available chair numbers. Initially, we add 0, 1, ldots, n-1 to idle. We also use a min-heap busy to store tuples (leaving, chair), where leaving represents the leaving time and chair represents the chair number.

We iterate through each friend's arrival time, leaving time, and index. For each friend, we first remove all friends from busy whose leaving time is less than or equal to the current friend's arrival time, and add their chair numbers back to idle. Then we pop a chair number from idle, assign it to the current friend, and add (leaving, chair) to busy. If the current friend's index is equal to targetFriend, we return the assigned chair number.

The time complexity is O(n times log n), and the space complexity is O(n). Here, n is the number of friends.

function smallestChair(times: number[][], targetFriend: number): number {
    const n = times.length;
    const idle = new MinPriorityQueue<number>();
    const busy = new PriorityQueue((a, b) => a[0] - b[0]);
    for (let i = 0; i < n; ++i) {
        times[i].push(i);
        idle.enqueue(i);
    }
    times.sort((a, b) => a[0] - b[0]);
    for (const [arrival, leaving, i] of times) {
        while (busy.size() > 0 && busy.front()[0] <= arrival) {
            idle.enqueue(busy.dequeue()[1]);
        }
        const j = idle.dequeue();
        if (i === targetFriend) {
            return j;
        }
        busy.enqueue([leaving, j]);
    }
    return -1;
}
func smallestChair(times [][]int, targetFriend int) int {
	idle := hp{}
	busy := hp2{}
	for i := range times {
		times[i] = append(times[i], i)
		heap.Push(&idle, i)
	}
	sort.Slice(times, func(i, j int) bool { return times[i][0] < times[j][0] })
	for _, e := range times {
		arrival, leaving, i := e[0], e[1], e[2]
		for len(busy) > 0 && busy[0].t <= arrival {
			heap.Push(&idle, heap.Pop(&busy).(pair).i)
		}
		j := heap.Pop(&idle).(int)
		if i == targetFriend {
			return j
		}
		heap.Push(&busy, pair{leaving, j})
	}
	return -1
}

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
}

type pair struct{ t, i int }
type hp2 []pair

func (h hp2) Len() int           { return len(h) }
func (h hp2) Less(i, j int) bool { return h[i].t < h[j].t || (h[i].t == h[j].t && h[i].i < h[j].i) }
func (h hp2) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *hp2) Push(v any)        { *h = append(*h, v.(pair)) }
func (h *hp2) Pop() any          { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
Try this approach in the editor

Complexity comparison

ApproachComplexity
Min-Heap Approach

Time Complexity: O(n log n), where n is the number of friends (and thus events). This is due to sorting the events and using heap operations.
Space Complexity: O(n) for storing event data and the heap.

Event Scheduling with Sets

Time Complexity: O(n log n) because of sorting events and TreeSet operations.
Space Complexity: O(n) to maintain maps and sets for event and chair management.

Priority Queue (Min-Heap)–

Complexity analysis

ApproachTimeSpaceWhen to Use
Min-Heap SimulationO(n log n)O(n)General case; ideal when modeling arrivals and departures with priority queues
Event Scheduling with Ordered SetsO(n log n)O(n)Useful when language libraries provide efficient ordered sets or trees

Frequently asked questions

Is The Number of the Smallest Unoccupied Chair easy or hard?

The problem is classified as Medium difficulty. The logic is straightforward once you recognize it as an event simulation problem, but managing two priority queues and correctly releasing chairs based on leave times requires careful implementation.

The Number of the Smallest Unoccupied Chair Python/Java solution

Python solutions typically use the heapq module to manage available chairs and active departures. Java implementations often rely on PriorityQueue with custom pairs storing leave time and chair number. Both follow the same event simulation strategy with O(n log n) complexity.

How to solve The Number of the Smallest Unoccupied Chair in O(n)?

An exact O(n) solution is generally not feasible because arrivals must be processed in sorted order and chair assignments require ordered retrieval. Sorting alone costs O(n log n). The practical optimal approach therefore uses heaps or ordered sets and runs in O(n log n) time.

What is the best approach for The Number of the Smallest Unoccupied Chair?

The most common solution uses a min-heap simulation. Friends are processed in order of arrival time, a heap tracks currently occupied chairs by leave time, and another heap stores available chair numbers. Each arrival releases chairs whose owners have left, then assigns the smallest available chair. This approach runs in O(n log n) time and O(n) space.

Is The Number of the Smallest Unoccupied Chair asked at Google/Amazon/Meta?

This problem reflects a common interview pattern involving event simulation and priority queues. Variants of the problem appear in interviews at companies like Google, Amazon, and Meta when testing heap usage, scheduling logic, and resource allocation algorithms.

What data structure is used in The Number of the Smallest Unoccupied Chair?

The core data structure is a min-heap (priority queue). One heap tracks the smallest available chair number, while another heap tracks occupied chairs ordered by leaving time. Some implementations also use ordered sets or maps to manage chair availability.

What is the time complexity of The Number of the Smallest Unoccupied Chair?

The optimal solution runs in O(n log n) time. Sorting friends by arrival takes O(n log n), and each heap operation for assigning or freeing a chair costs O(log n). Since each friend is inserted and removed from the heaps at most once, the total complexity remains O(n log n) with O(n) space.

Comments

Now write it yourselfClose this page and solve The Number of the Smallest Unoccupied Chair in the editor, without looking.
Practise The Number of the Smallest Unoccupied Chair