Opening the reading…
Opening the reading…
GREEDY › PART I
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →A platform is occupied from a train's arrival through its departure, including both endpoints because an arrival at the exact departure time still overlaps. Therefore, the required number of platforms is the largest number of train intervals covering the same moment. You do not need to decide which particular platform each train receives; only the number currently occupied matters.
The original pairing between arr[i] and dep[i] identifies each train, but it is not needed to count simultaneous trains. Sort all arrivals and all departures independently. Then compare the next event on each list: an arrival at or before the next departure increases the number of occupied platforms, while a strictly later arrival can reuse the platform released by that departure. The largest active count is the answer.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n log n) | Sorting the n arrivals and n departures costs O(n log n) in total, and the two pointers each move only forward, so the scan processes at most 2n events without revisiting one. |
| Space | O(1) extra, excluding the input arrays | The scan uses four integer variables and the sorting is in place for the supplied vectors. The returned integer has constant output size, and the bound does not degrade with any input shape. |
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
int minPlatforms(vector<int>& arr, vector<int>& dep) {
sort(arr.begin(), arr.end());
sort(dep.begin(), dep.end());
int i = 0;
int j = 0;
int current = 0;
int answer = 0;
int n = static_cast<int>(arr.size());
while (i < n) {
if (arr[i] <= dep[j]) {
++current;
answer = max(answer, current);
++i;
} else {
--current;
++j;
}
}
return answer;
}
};The placement of the comparison and update is the core of the solution. An arrival is counted before answer is updated, because the new train needs a platform immediately. A departure only reduces current; it cannot create a larger requirement. Since every arrival is paired with a departure no earlier than itself, the departure pointer remains valid whenever the loop still has an arrival to process.