#3168

Minimum Number of Chairs in a Waiting Room

Easy
StringSimulationSimulationCounting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution efficiently counts the number of people in the waiting room using a single pass through the string. We maintain a count of current people and track the maximum number of people present at any time, which directly gives us the number of chairs needed.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable to track the current number of people in the waiting room.
  2. 2Step 2: Initialize a variable to track the maximum number of people at any time.
  3. 3Step 3: Iterate through each character in the string: increment for 'E' and decrement for 'L'. Update the maximum if the current number exceeds it.
solution.py11 lines
1def min_chairs(s):
2    current_people = 0
3    max_people = 0
4    for event in s:
5        if event == 'E':
6            current_people += 1
7        else:
8            current_people -= 1
9        max_people = max(max_people, current_people)
10    return max_people
11

Complexity note: The complexity is O(n) because we only make a single pass through the string, processing each character once.

  • 1The maximum number of people in the waiting room at any time is equal to the number of chairs needed.
  • 2Each 'E' increases the count while each 'L' decreases it.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.