Minimum Number of Platforms

Posted: 19 Oct, 2020
Difficulty: Moderate

PROBLEM STATEMENT

Try Problem

You have been given two arrays, 'AT' and 'DT', representing the arrival and departure times of all trains that reach a railway station.

Your task is to find the minimum number of platforms required for the railway station so that no train needs to wait.

Note :
1. Every train will depart on the same day and the departure time will always be greater than the arrival time. For example, A train with arrival time 2240 and departure time 1930 is not possible.

2. Time will be given in 24H format and colons will be omitted for convenience. For example, 9:05AM will be given as "905", or 9:10PM will be given as "2110".

3. Also, there will be no leading zeroes in the given times. For example, 12:10AM will be given as “10” and not as “0010”.
Input Format
The first line of input contains an integer 'T' representing the number of test cases.

The first line of each test case contains an integer 'N', representing the total number of trains.

The second line of each test case contains 'N' single-spaced separated elements of the array 'AT',  representing the arrival times of all the trains.

The third line of each test case contains 'N' single-spaced separated elements of the array 'DT', representing the departure times of all the trains.
Output Format:
For each test case, return the minimum number of platforms required for the railway station so that no train needs to wait.
Note :
You don't need to print the output, it has already been taken care of. You just need to implement the given function.
Follow up :
Try to solve the problem in O(N) time and O(1) space.
Constraints:
1 <= T <= 10
1 <= N <= 50000
0 <= AT[i] <= DT[i] <= 2359

Where 'AT[i]' and 'DT[i]' are the elements of the arrival and the departure arrays respectively.

Time limit: 1 sec
Approach 1

The main idea behind this approach is to use an array, 'PLATFORMS', to store the number of platforms required at different points of time. Now, since the time range is from 0 to 2359 in the 24 hour format, we declare the array 'PLATFORMS' with a size of 2360 (as we need values from 0 to 2359) and all values initialized to 0.

 

Now, we traverse both the arrays together and do the following :

 

  • For all points of time between the arrival and departure of each train (both inclusive), we increment the number of platforms by 1 i.e.
    for all points of time >= ‘AT[i]’ and <= ‘DT[i]’

            PLATFORMS[time]++

 

  • Now, whenever we increment the number of platforms at any point of time (as discussed in the above step), we update the answer if the number of platforms is greater than the answer.
Try Problem