# Minimum platforms based on Train arrival and departure

--

Given 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 is kept waiting.

Consider that all the trains arrive on the same day and leave on the same day. Arrival and departure time can never be the same for a train but we can have arrival time of one train equal to departure time of the other. At any given instance of time, same platform can not be used for both departure of a train and arrival of another train. In such cases, we need different platforms**.**

**Example:**

**Input**: n = 6

arr[] = {0900, 0940, 0950, 1100, 1500, 1800}

dep[] = {0910, 1200, 1120, 1130, 1900, 2000}

**Output**: 3

- First brute force approach is to sort both arrival and departure arrays and then compare each arrival with the departure
- Initially there would be 1 platform; if a train arrives after the previous one leaves then the same platform can be used; if the train arrives before previous train departs then there will be a need of another platform
- We will increase the number of platform when train arrival is before the previous train departure; when arrival[i] is less than departure[j] where j<i
- We will decrease the number of platform when train arrival is after the previous train departure; when arrival[i] is greater than departure[j] where j<i

`static int findPlatform(int arr[], int dep[], int n)`

{

Arrays.sort(arr);

Arrays.sort(dep);

int i=1;

int j=0;

int platform=1;

int result=0;

while(i<n && j<n){

if(arr[i]<dep[j]){

platform++;

i++;

}

else if(arr[i]>dep[j]){

platform--;

j++;

}

if(result<platform)

result=platform;

}

return result;

}

- The time complexity of this algorithm is O(nlogn) since we need to sort each of the array values
- We can opt for a constant extra space; an array platforms of size 2361 to store the platforms one might need in realtime
- 2361 because the time range is from 00:00 to 23:60
- we will increment the value of platforms at i, where i the time of arrival of a train; and we will decrement the value of platform at i, where i will be the departure time of train +1( to avoid overlapping and suffice all test cases )
- Then we will add up the platforms values and get an aggregate result for each platforms[i] from 1->2361
- This algorithm takes O(n) time complexity

`static int findPlatform(int arr[], int dep[], int n)`

{

int[] platforms=new int[2361];

int result=1;

for(int i=0;i<n;i++){

platforms[arr[i]]++;

platforms[dep[i]+1]--;

}

for(int i=1;i<2361;i++){

platforms[i]=platforms[i]+platforms[i-1];

result=Math.max(result,platforms[i]);

}

return result;

}