Given two arrays arr[] and dep[], that represent the arrival and departure time of i-th train respectively. Find the minimum number of platforms required so that no train has to wait. If the departure time of one train is the same as the arrival time of another train, both trains cannot use the same platform at that time.
Note: Time intervals are in the 24-hour format (HHMM), where the first two characters represent hour (between 00 to 23) and the last two characters represent minutes (this will be <= 59 and >= 0). Leading zeros for hours less than 10 are optional (e.g., 0900 is the same as 900).
Examples:
Input: arr[] = [1000, 935, 1100], dep[] = [1200, 1240, 1130] Output: 3 Explanation: We need 3 platforms for the arrival of these trains because all three trains have overlapping time.
Input: arr[] = [900, 1235, 1100], dep[] = [1000, 1240, 1200] Output: 1 Explanation: Only 1 platform is required for all the three trains because the departure time of each train is less then arrival time of next train.
[Naive Approach] Using Two Nested Loops - O(n2) time and O(1) space
Run two nested loops, the outer loop from start to end and the inner loop from i+1 to end.
For every iteration of the outer loop, find the count of intervals that intersect with the current interval.
Update the answer with the maximum count of overlap in each iteration of the outer loop.
C++
#include<iostream>#include<vector>#include<algorithm>usingnamespacestd;intminPlatform(vector<int>&arr,vector<int>&dep){intn=arr.size();intres=0;for(inti=0;i<n;i++){// Initially one platform is neededintcnt=1;for(intj=i+1;j<n;j++){// check for overlapif((arr[i]>=arr[j]&&arr[i]<=dep[j])||(arr[j]>=arr[i]&&arr[j]<=dep[i]))cnt++;}res=max(cnt,res);}returnres;}intmain(){vector<int>arr={1000,935,1100};vector<int>dep={1200,1240,1130};cout<<minPlatform(arr,dep)<<endl;return0;}
Java
importjava.util.*;classGfG{staticintminPlatform(int[]arr,int[]dep){intn=arr.length;intres=0;for(inti=0;i<n;i++){// Initially one platform is neededintcnt=1;for(intj=i+1;j<n;j++){// check for overlapif((arr[i]>=arr[j]&&arr[i]<=dep[j])||(arr[j]>=arr[i]&&arr[j]<=dep[i]))cnt++;}res=Math.max(cnt,res);}returnres;}publicstaticvoidmain(String[]args){int[]arr={1000,935,1100};int[]dep={1200,1240,1130};System.out.println(minPlatform(arr,dep));}}
Python
defminPlatform(arr,dep):n=len(arr)res=0foriinrange(n):# Initially one platform is neededcnt=1forjinrange(i+1,n):# check for overlapif((arr[i]>=arr[j]andarr[i]<=dep[j])or(arr[j]>=arr[i]andarr[j]<=dep[i])):cnt+=1res=max(cnt,res)returnresarr=[1000,935,1100]dep=[1200,1240,1130]print(minPlatform(arr,dep))
C#
usingSystem;classGfG{staticintminPlatform(int[]arr,int[]dep){intn=arr.Length;intres=0;for(inti=0;i<n;i++){// Initially one platform is neededintcnt=1;for(intj=i+1;j<n;j++){// check for overlapif((arr[i]>=arr[j]&&arr[i]<=dep[j])||(arr[j]>=arr[i]&&arr[j]<=dep[i]))cnt++;}res=Math.Max(cnt,res);}returnres;}staticvoidMain(){int[]arr={1000,935,1100};int[]dep={1200,1240,1130};Console.WriteLine(minPlatform(arr,dep));}}
JavaScript
functionminPlatform(arr,dep){letn=arr.length;letres=0;for(leti=0;i<n;i++){// Initially one platform is neededletcnt=1;for(letj=i+1;j<n;j++){// check for overlapif((arr[i]>=arr[j]&&arr[i]<=dep[j])||(arr[j]>=arr[i]&&arr[j]<=dep[i]))cnt++;}res=Math.max(cnt,res);}returnres;}letarr=[1000,935,1100];letdep=[1200,1240,1130];console.log(minPlatform(arr,dep));
Output
3
[Expected Approach] Traverse all events in sorted order - O(n log(n)) Time and O(1) Space
The idea is to consider all events in sorted order. Once the events are in sorted order, trace the number of trains at any time keeping track of trains that have arrived, but not departed.
Below are the steps
Sort arr[] in ascending order
Sort dep[] in ascending order
Now traverse all events in ascending order, we mainly use the idea of the merge() function of merge sort here to merge two sorted arrays.
All events are sorted by time. Total platforms at any time can be obtained by subtracting total departures from total arrivals by that time.
Time Event Type Count at this Time 9:00 Arrival 1 9:10 Departure 0 9:40 Arrival 1 9:50 Arrival 2 11:00 Arrival 3 11:20 Departure 2 11:30 Departure 1 12:00 Departure 0 15:00 Arrival 1 18:00 Arrival 2 19:00 Departure 1 20:00 Departure 0
Minimum Platforms = Maximum platforms needed at any time = 3
C++
#include<iostream>#include<vector>#include<algorithm>usingnamespacestd;intminPlatform(vector<int>&arr,vector<int>&dep){intn=arr.size();intres=0;sort(arr.begin(),arr.end());sort(dep.begin(),dep.end());// plat_needed indicates number of platforms// needed at a timeintcnt=1;inti=1,j=0;// Similar to merge in merge sort to process// all events in sorted orderwhile(i<n&&j<n){// If next event in sorted order is arrival,// increment count of platforms neededif(arr[i]<=dep[j]){cnt++;i++;}// Else decrement count of platforms neededelseif(arr[i]>dep[j]){cnt--;j++;}// Update result if neededres=max(res,cnt);}returnres;}intmain(){vector<int>arr={900,940,950,1100,1500,1800};vector<int>dep={910,1200,1120,1130,1900,2000};cout<<minPlatform(arr,dep);return0;}
Java
importjava.util.*;classGfG{staticintminPlatform(int[]arr,int[]dep){intn=arr.length;intres=0;Arrays.sort(arr);Arrays.sort(dep);// plat_needed indicates number of platforms// needed at a timeintcnt=1;inti=1,j=0;// Similar to merge in merge sort to process// all events in sorted orderwhile(i<n&&j<n){// If next event in sorted order is arrival,// increment count of platforms neededif(arr[i]<=dep[j]){cnt++;i++;}// Else decrement count of platforms neededelseif(arr[i]>dep[j]){cnt--;j++;}// Update result if neededres=Math.max(res,cnt);}returnres;}publicstaticvoidmain(String[]args){int[]arr={900,940,950,1100,1500,1800};int[]dep={910,1200,1120,1130,1900,2000};System.out.println(minPlatform(arr,dep));}}
Python
defminPlatform(arr,dep):n=len(arr)res=0arr.sort()dep.sort()# plat_needed indicates number of platforms# needed at a timecnt=1i=1j=0# Similar to merge in merge sort to process# all events in sorted orderwhilei<nandj<n:# If next event in sorted order is arrival,# increment count of platforms neededifarr[i]<=dep[j]:cnt+=1i+=1# Else decrement count of platforms neededelse:cnt-=1j+=1# Update result if neededres=max(res,cnt)returnresarr=[900,940,950,1100,1500,1800]dep=[910,1200,1120,1130,1900,2000]print(minPlatform(arr,dep))
C#
usingSystem;classGfG{staticintminPlatform(int[]arr,int[]dep){intn=arr.Length;intres=0;Array.Sort(arr);Array.Sort(dep);// plat_needed indicates number of platforms// needed at a timeintcnt=1;inti=1,j=0;// Similar to merge in merge sort to process// all events in sorted orderwhile(i<n&&j<n){// If next event in sorted order is arrival,// increment count of platforms neededif(arr[i]<=dep[j]){cnt++;i++;}// Else decrement count of platforms neededelseif(arr[i]>dep[j]){cnt--;j++;}// Update result if neededres=Math.Max(res,cnt);}returnres;}staticvoidMain(){int[]arr={900,940,950,1100,1500,1800};int[]dep={910,1200,1120,1130,1900,2000};Console.WriteLine(minPlatform(arr,dep));}}
JavaScript
functionminPlatform(arr,dep){letn=arr.length;letres=0;arr.sort((a,b)=>a-b);dep.sort((a,b)=>a-b);// plat_needed indicates number of platforms// needed at a timeletcnt=1;leti=1,j=0;// Similar to merge in merge sort to process// all events in sorted orderwhile(i<n&&j<n){// If next event in sorted order is arrival,// increment count of platforms neededif(arr[i]<=dep[j]){cnt++;i++;}// Else decrement count of platforms neededelseif(arr[i]>dep[j]){cnt--;j++;}// Update result if neededres=Math.max(res,cnt);}returnres;}letarr=[900,940,950,1100,1500,1800];letdep=[910,1200,1120,1130,1900,2000];console.log(minPlatform(arr,dep));
Output
3
[Expected Approach 2] Sweep Line
The Sweep Line Algorithm is an efficient technique for solving interval-based problems.
It works by treating each train's arrival and departure times as events on a timeline. By processing these events in time order, we can track how many trains are at the station at any moment, which directly gives the number of platforms needed at that time. The maximum overlap of trains during this process determines the minimum number of platforms required.
Step by Step implementation:
Create an array v[] of size greater than the maximum departure time. This array will help track the number of platforms needed at each time.
Mark arrivals and departures:
For each arrival time, increment v[arrival_time] by 1, indicating that a platform is needed.
For each departure time, decrement v[departure_time + 1] by 1, indicating that a platform is freed as the train has left.
Iterate through v[] and compute the cumulative sum.
The running sum keeps track of the number of trains present at any given time.
The maximum value encountered represents the minimum number of platforms required.
C++
#include<iostream>#include<vector>usingnamespacestd;intminPlatform(vector<int>&arr,vector<int>&dep){intn=arr.size();intres=0;// Find the max Departure time intmaxDep=dep[0];for(inti=1;i<n;i++){maxDep=max(maxDep,dep[i]);}vector<int>v(maxDep+2,0);// Increment the count at the arrival time and decrement// at the departure timefor(inti=0;i<n;i++){v[arr[i]]++;v[dep[i]+1]--;}intcount=0;// Iterate over the vector and keep track of the maximum// sum seen so farfor(inti=0;i<=maxDep+1;i++){count+=v[i];res=max(res,count);}returnres;}intmain(){vector<int>arr={900,940,950,1100,1500,1800};vector<int>dep={910,1200,1120,1130,1900,2000};cout<<minPlatform(arr,dep);return0;}
Java
importjava.util.Arrays;classGfG{staticintminPlatform(int[]arr,int[]dep){intn=arr.length;intres=0;// Find the max Departure time intmaxDep=dep[0];for(inti=1;i<n;i++){maxDep=Math.max(maxDep,dep[i]);}int[]v=newint[maxDep+2];// Increment the count at the arrival time and decrement// at the departure timefor(inti=0;i<n;i++){v[arr[i]]++;v[dep[i]+1]--;}intcount=0;// Iterate over the array and keep track of the maximum// sum seen so farfor(inti=0;i<=maxDep+1;i++){count+=v[i];res=Math.max(res,count);}returnres;}publicstaticvoidmain(String[]args){int[]arr={900,940,950,1100,1500,1800};int[]dep={910,1200,1120,1130,1900,2000};System.out.println(minPlatform(arr,dep));}}
Python
defminPlatform(arr,dep):n=len(arr)res=0# Find the max Departure time maxDep=max(dep)v=[0]*(maxDep+2)# Increment the count at the arrival time and decrement# at the departure timeforiinrange(n):v[arr[i]]+=1v[dep[i]+1]-=1count=0# Iterate over the list and keep track of the maximum# sum seen so farforiinrange(maxDep+2):count+=v[i]res=max(res,count)returnresif__name__=="__main__":arr=[900,940,950,1100,1500,1800]dep=[910,1200,1120,1130,1900,2000]print(minPlatform(arr,dep))
C#
usingSystem;classGfG{staticintminPlatform(int[]arr,int[]dep){intn=arr.Length;intres=0;// Find the max Departure time intmaxDep=dep[0];for(inti=1;i<n;i++){maxDep=Math.Max(maxDep,dep[i]);}int[]v=newint[maxDep+2];// Increment the count at the arrival time and decrement// at the departure timefor(inti=0;i<n;i++){v[arr[i]]++;v[dep[i]+1]--;}intcount=0;// Iterate over the array and keep track of the maximum// sum seen so farfor(inti=0;i<=maxDep+1;i++){count+=v[i];res=Math.Max(res,count);}returnres;}staticvoidMain(string[]args){int[]arr={900,940,950,1100,1500,1800};int[]dep={910,1200,1120,1130,1900,2000};Console.WriteLine(minPlatform(arr,dep));}}
JavaScript
functionminPlatform(arr,dep){letn=arr.length;letres=0;// Find the max Departure time letmaxDep=Math.max(...dep);letv=newArray(maxDep+2).fill(0);// Increment the count at the arrival time and decrement// at the departure timefor(leti=0;i<n;i++){v[arr[i]]++;v[dep[i]+1]--;}letcount=0;// Iterate over the array and keep track of the maximum// sum seen so farfor(leti=0;i<=maxDep+1;i++){count+=v[i];res=Math.max(res,count);}returnres;}// Driver Code letarr=[900,940,950,1100,1500,1800];letdep=[910,1200,1120,1130,1900,2000];console.log(minPlatform(arr,dep));
Output
3
Time Complexity: O(n + k), where n is the number of trains and k is the maximum value present in the arrays. Auxiliary space: O(k), where k is the maximum value present in both the arrays.