Minimum Number of Chairs in a Waiting Room

Problem Description

Imagine you’re at a waiting room, and it’s packed! You’ve got people coming in and out like it’s a revolving door. The problem is, you need to figure out the minimum number of chairs required to accommodate everyone without leaving anyone standing awkwardly in the corner.

In this delightful scenario, ‘E’ represents a person entering the room, and ‘L’ represents a person leaving. Your task is to calculate the maximum number of chairs needed at any point in time. Because let’s be honest, nobody wants to be that person who has to awkwardly stand while everyone else is comfortably seated.

Code Solution


class Solution {
  public int minimumChairs(String s) {
    int ans = 0;
    int chairs = 0;

    for (final char c : s.toCharArray()) {
      chairs += c == 'E' ? 1 : -1;
      ans = Math.max(ans, chairs);
    }

    return ans;
  }
}

Approach Explanation

The approach here is as straightforward as counting how many friends you can fit into your tiny apartment. We iterate through the string, adjusting the number of chairs based on whether someone enters or leaves. Each time someone enters, we increase the chair count, and when someone leaves, we decrease it. The maximum number of chairs at any point is our answer. Simple, right?

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n), where n is the length of the string. We traverse the string once.
Space Complexity O(1), as we are using a constant amount of space for our variables.

Real-World Example

Picture this: You’re at a coffee shop, and it’s a Saturday morning. People are coming in for their caffeine fix, and some are leaving after their quick pit stop. You need to figure out how many chairs you need to set up to ensure no one is left standing awkwardly by the door, clutching their coffee like a lifeline. This problem is just like that, but with a bit more coding magic!

Similar Problems

  • 2-Sum Solution in Java
  • 3-Sum Solution in Java
  • 4-Sum Solution in Java