Facebook Pixel

3168. Minimum Number of Chairs in a Waiting Room

EasyStringSimulation
Leetcode Link

Problem Description

You are given a string s representing a sequence of events. Each character in the string can either be E or L:

  • E: A person enters the waiting room and occupies a chair.
  • L: A person leaves the waiting room, freeing up a chair.

The task is to determine the minimum number of chairs needed so that, at any given time, there is a chair available for every person who enters the waiting room. The waiting room is initially empty.

Intuition

To solve this problem, we simulate the sequence of events described by the string s while keeping track of the number of chairs in use and the number of chairs available.

We use two variables:

  • cnt: This keeps track of the minimum number of chairs currently required.
  • left: This accounts for empty chairs that are available after someone leaves.

As we traverse through each character in the string:

  • If the character is E, we check if there are any empty chairs (left). If there are, we simply decrement the number of available chairs (left). If not, it means we need an additional chair, so we increment cnt.
  • If the character is L, we increase the count of available chairs (left) because a person has left, freeing up a chair.

By the end of the traversal, cnt will represent the minimum number of chairs needed to accommodate all incoming people without delay.

Solution Approach

We utilize a simple simulation approach to determine the minimum number of chairs needed in the waiting room:

  1. Initialize two variables:

    • cnt to count the minimum number of chairs required.
    • left to track the number of available empty chairs at any time.
  2. Traverse the string s character by character:

    • If the current character is 'E', check if there is an available empty chair (left > 0):
      • If there is an empty chair, decrement left since an incoming person will occupy it.
      • If no empty chairs are available, increase cnt to indicate a need for an additional chair.
    • If the current character is 'L', increment left as a person leaving frees up a chair.
  3. The final value of cnt after processing the entire string represents the minimum number of chairs needed.

On a high-level view, this solution uses a greedy approach with two counters to dynamically manage the allocation and deallocation of chairs efficiently and ensure optimal usage at any time given the sequence of events.

Here’s the code implementing this solution:

class Solution:
    def minimumChairs(self, s: str) -> int:
        cnt = left = 0
        for c in s:
            if c == "E":
                if left:
                    left -= 1
                else:
                    cnt += 1
            else:
                left += 1
        return cnt

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution approach with a small example string s = "EELLE":

  1. Initialize Variables:

    • cnt = 0 (This tracks the minimum number of chairs needed).
    • left = 0 (This tracks available empty chairs).
  2. Process Each Character:

    • Character 1 ('E'):

      • Since there are no empty chairs (left = 0), increment cnt to 1.
      • Now, cnt = 1, left = 0.
    • Character 2 ('E'):

      • Again, no empty chairs are available (left = 0), so increment cnt to 2.
      • Now, cnt = 2, left = 0.
    • Character 3 ('L'):

      • A person leaves, which frees up a chair, so increment left by 1.
      • Now, cnt = 2, left = 1.
    • Character 4 ('L'):

      • Another person leaves, freeing up another chair, so increment left to 2.
      • Now, cnt = 2, left = 2.
    • Character 5 ('E'):

      • An entering person uses one of the empty chairs, so decrement left by 1.
      • Now, cnt = 2, left = 1.
  3. Final Result:

    • After processing the entire string, cnt = 2, which represents the minimum number of chairs needed throughout the events to accommodate all entering persons without delay.

Solution Implementation

1class Solution:
2    def minimumChairs(self, s: str) -> int:
3        # Initialize counters for minimum chairs needed and people who have left
4        min_chairs_needed = 0
5        people_left = 0
6      
7        # Iterate over each character in the string
8        for char in s:
9            if char == "E":  # If the event is someone exiting
10                if people_left > 0:
11                    # Reduce the count of people who've left but haven't been matched
12                    people_left -= 1
13                else:
14                    # Increment the count of required chairs as no one has left
15                    min_chairs_needed += 1
16            else:
17                # Increase the count of people who have entered
18                people_left += 1
19
20        return min_chairs_needed
21
1class Solution {
2    /**
3     * This method calculates the minimum number of chairs required.
4     * 'E' indicates a person entering, and 'L' indicates a person leaving.
5     *
6     * @param s A string where each character represents an entry ('E') or leave ('L').
7     * @return The minimum number of chairs needed.
8     */
9    public int minimumChairs(String s) {
10        int chairsNeeded = 0; // To track the total number of chairs required.
11        int currentChairs = 0; // To track the current available chairs.
12
13        // Iterate over each character in the string.
14        for (int i = 0; i < s.length(); ++i) {
15            if (s.charAt(i) == 'E') { // If the character is 'E', someone enters.
16                if (currentChairs > 0) {
17                    // Use one of the available chairs.
18                    --currentChairs; 
19                } else {
20                    // No available chairs, so we need a new one.
21                    ++chairsNeeded;
22                }
23            } else { // If the character is 'L', someone leaves.
24                // Increase the count of available chairs.
25                ++currentChairs;
26            }
27        }
28        return chairsNeeded; // Return the total number of chairs needed.
29    }
30}
31
1class Solution {
2public:
3    int minimumChairs(std::string s) {
4        int chairCount = 0; // Track number of chairs needed
5        int waitingPeople = 0; // Track number of people who are waiting
6
7        for (char& c : s) {
8            if (c == 'E') { // When a person exits
9                if (waitingPeople > 0) {
10                    // Decrement waiting people if there are any
11                    --waitingPeople;
12                } else {
13                    // If no one is waiting, increment chair count
14                    ++chairCount;
15                }
16            } else {
17                // Increment waiting people when a person enters
18                ++waitingPeople;
19            }
20        }
21        return chairCount;
22    }
23};
24
1// This function calculates the minimum number of chairs needed given a string of 'E's (entering) and 'L's (leaving).
2function minimumChairs(s: string): number {
3    // Initialize counters: `cnt` for counting chairs needed, `left` for tracking people leaving without needing a chair.
4    let cnt = 0;
5    let left = 0;
6
7    // Iterate over each character in the input string `s`.
8    for (const c of s) {
9        if (c === 'E') { // If someone is entering 'E',
10            if (left > 0) {
11                // If there are people who have left ('L'), decrement the `left` counter.
12                --left;
13            } else {
14                // If no one has left, increment the chair count `cnt` as an additional chair is needed.
15                ++cnt;
16            }
17        } else { // If someone is leaving 'L',
18            // Increment the `left` counter indicating a chair can be reused by the next 'E'.
19            ++left;
20        }
21    }
22
23    // Return the total number of chairs required.
24    return cnt;
25}
26

Time and Space Complexity

The time complexity of the code is O(n), where n is the length of the string s. This is because the code iterates over each character in the string exactly once, performing constant-time operations for each character. The space complexity is O(1), as it uses a fixed amount of extra space (variables cnt and left) irrespective of the input size.

Learn more about how to find time and space complexity quickly.


Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

Which type of traversal does breadth first search do?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!


Load More