![]() |
VOOZH | about |
Given the arrival and departure times of all trains that reach a railway station, find the minimum number of platforms required for the railway station so that no train waits. We are given two arrays that represent arrival and departure times of trains that stop.
Examples:
Input: arr[] = {0900, 0940, 0950, 1100, 1500, 1800}, dep[] = {0910, 1200, 1120, 1130, 1900, 2000}
Output: 3
Explanation: There are at-most three trains at a time (time between 11:00 to 11:20).Input: arr[] = {0900, 1235, 1100}, dep[] = {1000, 1240, 1200}
Output: 1
Explanation: All train times are mutually exclusive. So we need only one platform.
Approach: To solve the problem, follow the below idea:
The problem can be solved using a multiset. We can insert all the arrival and departure times in a multiset in the form of pairs, where the first value of the pair tells the arrival/departure time and second value tells whether it's arrival or departure represented by 'a' or 'd' respectively.
We can maintain a variable, say occupiedPlatforms to keep track of the platforms currently in use. Now, we can iterate over the multiset and for each element, check if its arrival time or departure time.
- If the next time is an arrival time, then we increment occupiedPlatforms by 1 as we need more platforms on arrival of a train.
- If the next time is a departure time, then we decrement occupiedPlatforms by 1 as one platform has become empty on departure of a train.
The maximum value of occupiedPlatforms at any point is the minimum number of platforms required.
Below is the implementation of the above approach:
Minimum Number of Platforms Required = 3
Time Complexity: O(N* LogN), Since we are inserting into multiset and it maintain elements in sorted order. So N insert operations in multiset requires N*LogN time complexity.
Auxiliary Space:O(N), we are using multiset which will have 2*N elements.
Related Article:Minimum Number of Platforms Required for a Railway/Bus Station