The Number of the Smallest Unoccupied Chair - 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.

Input & Output

Example 1 — Basic Party Scenario
$ Input: times = [[1,4],[2,3],[4,6]], targetFriend = 1
Output: 1
💡 Note: Friend 0 arrives at time 1, sits in chair 0. Friend 1 arrives at time 2, sits in chair 1 (smallest available). Friend 1 leaves at time 3, but we already found the answer.
Example 2 — Chair Reuse
$ Input: times = [[3,10],[1,5],[2,6]], targetFriend = 0
Output: 2
💡 Note: Friend 1 arrives at time 1, sits in chair 0. Friend 2 arrives at time 2, sits in chair 1. Friend 0 arrives at time 3, sits in chair 2.
Example 3 — Immediate Chair Reuse
$ Input: times = [[1,2],[2,3],[3,4]], targetFriend = 2
Output: 0
💡 Note: Friend 0: arrives at 1, sits in chair 0, leaves at 2. Friend 1: arrives at 2, sits in chair 0 (just freed), leaves at 3. Friend 2: arrives at 3, sits in chair 0 (just freed again).

Constraints

  • n == times.length
  • 2 ≤ n ≤ 104
  • 1 ≤ arrivali < leavingi ≤ 105
  • 0 ≤ targetFriend ≤ n - 1
  • Each arrivali is distinct

Visualization

Tap to expand
Chair Assignment at a Partytimes = [[1,4],[2,3],[4,6]], targetFriend = 1Friend 0: [1,4]Friend 1: [2,3]Friend 2: [4,6]Arrives: t=1Arrives: t=2 (target)Arrives: t=40123Friend 0Friend 1AvailableAvailableAnswer: Chair 1Friend 1 gets the smallest available chair when arriving at time 2
Understanding the Visualization
1
Input
Times array with [arrival, departure] and target friend
2
Process
Assign chairs in chronological order, always using smallest available
3
Output
Chair number that target friend sits on
Key Takeaway
🎯 Key Insight: Process events chronologically and always assign the numerically smallest available chair
Asked in
Amazon 15 Google 12 Microsoft 8 Facebook 6
28.5K Views
Medium Frequency
~25 min Avg. Time
893 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen