[Geeks for Geeks] Minimum Platforms

Minimum Platforms

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.

  • Time : O(nlogn)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
//Function to find the minimum number of platforms required at the
//railway station such that no train waits.
int findPlatform(int arr[], int dep[], int n) {
int res = 0;
vector<pair<int,int>> A;
for(int i = 0; i < n; i++) A.push_back({arr[i], dep[i]});
sort(begin(A), end(A));

priority_queue<int, vector<int>, greater<int>> pq;
for(auto& p : A) {
auto a = p.first, d = p.second;
while(!pq.empty() and pq.top() < a) pq.pop();
pq.push(d);
res = max(res, (int)pq.size());
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/minimum-platforms/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.