function findPlatform(arr: number[], dep: number[], n: number): number {
arr.sort((a, b) => a - b);
dep.sort((a, b) => a - b);
let platform_needed = 1, result = 1;
let i = 1, j = 0;
while (i < n && j < n) {
if (arr[i] <= dep[j]) {
platform_needed++;
i++;
if (platform_needed > result) result = platform_needed;
} else {
platform_needed--;
j++;
}
}
return result;
}
const arr = [900, 940, 950, 1100, 1500, 1800];
const dep = [910, 1200, 1120, 1130, 1900, 2000];
console.log(findPlatform(arr, dep, arr.length));The function sorts arrival and departure times. It uses two pointers to track trains arriving and leaving. When a train arrives before the earliest departure, we need an extra platform. When a train departs, a platform is freed. The maximum platforms needed at any time is 3.
const arrivals = [1000, 1010, 1025, 1030]; const departures = [1015, 1020, 1035, 1040]; function minPlatforms(arr: number[], dep: number[]): number { arr.sort((a, b) => a - b); dep.sort((a, b) => a - b); let platforms = 1, maxPlatforms = 1; let i = 1, j = 0; while (i < arr.length && j < dep.length) { if (arr[i] <= dep[j]) { platforms++; i++; if (platforms > maxPlatforms) maxPlatforms = platforms; } else { platforms--; j++; } } return maxPlatforms; } console.log(minPlatforms(arrivals, departures));
The trains overlap such that at one point 2 trains are at the station simultaneously, so 2 platforms are needed.
Sorting arrivals and departures separately allows us to process all events in chronological order, comparing the next arrival and departure to count how many trains are at the station simultaneously.
function findMinPlatforms(arr: number[], dep: number[]): number {
arr.sort();
dep.sort();
let platforms = 1, maxPlatforms = 1;
let i = 1, j = 0;
while (i < arr.length && j < dep.length) {
if (arr[i] < dep[j]) {
platforms++;
i++;
if (platforms > maxPlatforms) maxPlatforms = platforms;
} else {
platforms--;
j++;
}
}
return maxPlatforms;
}
const arrivals = [900, 940, 950, 1100];
const departures = [910, 1200, 1120, 1130];
console.log(findMinPlatforms(arrivals, departures));Using sort() without a compare function sorts numbers as strings, so 950 comes before 940, causing wrong platform count.
Sorting arrivals and departures separately and using two pointers is efficient (O(n log n)) and scalable for large inputs. Checking all pairs is too slow. Hash map counting each minute is memory heavy. Sorting only arrivals misses departure order.