Leetcode 3168. Minimum Number of Chairs in a Waiting Room
You’re given a list of tuples representing the arrival and departure times of people visiting a waiting room. Your task is to determine the minimum number of chairs required such that no person has to wait standing.
Each tuple (a, b) represents a visitor who arrives at time a
and leaves at time b
.
Input: [(1, 4), (2, 3), (3, 6), (5, 7)]
Output: 3
Here’s how you might implement this in C++:
#include <iostream>
#include <vector>
#include <algorithm>
int minChairsRequired(std::vector<std::pair<int, int>> intervals) {
std::vector<int> arrivals, departures;
for (auto interval : intervals) {
arrivals.push_back(interval.first);
departures.push_back(interval.second);
}
std::sort(arrivals.begin(), arrivals.end());
std::sort(departures.begin(), departures.end());
int arrivalIdx = 0, departureIdx = 0;
int currentChairs = 0, maxChairs = 0;
while (arrivalIdx < arrivals.size()) {
if (arrivals[arrivalIdx] < departures[departureIdx]) {
currentChairs++;
arrivalIdx++;
if (currentChairs > maxChairs) {
maxChairs = currentChairs;
}
} else {
currentChairs--;
departureIdx++;
}
}
return maxChairs;
}
int main() {
std::vector<std::pair<int, int>> intervals = \{\{1, 4}, {2, 3}, {3, 6}, {5, 7}};
std::cout << "Minimum Number of Chairs Required: " << minChairsRequired(intervals) << std::endl;
return 0;
}
Given that sorting dominates, the overall time complexity is O(n log n), which is efficient enough for n up to 10^4.
The algorithm separates arrival and departure times, sorts them, and then simulates room usage to find the maximum number of chairs required at any point in time. This solution efficiently handles the problem within the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?