function findPlatform(arr, dep) {
arr.sort((a, b) => a - b);
dep.sort((a, b) => a - b);
let platform_needed = 1, max_platforms = 1;
let i = 1, j = 0;
while (i < arr.length && j < dep.length) {
if (arr[i] <= dep[j]) {
platform_needed++;
i++;
if (platform_needed > max_platforms) max_platforms = platform_needed;
} else {
platform_needed--;
j++;
}
}
return max_platforms;
}
const arrivals = [900, 940, 950, 1100, 1500, 1800];
const departures = [910, 1200, 1120, 1130, 1900, 2000];
console.log(findPlatform(arrivals, departures));The code sorts arrival and departure times. It then uses two pointers to count how many trains are at the station simultaneously. The maximum count is the minimum number of platforms needed.
For the given times, the maximum overlap is 3 trains at once.
The key is to find the maximum number of trains that are at the station simultaneously. Sorting arrival and departure times helps track overlaps efficiently.
function findPlatform(arr, dep) {
arr.sort();
dep.sort();
let platform_needed = 1, max_platforms = 1;
let i = 1, j = 0;
while (i < arr.length && j < dep.length) {
if (arr[i] <= dep[j]) {
platform_needed++;
i++;
if (platform_needed > max_platforms) max_platforms = platform_needed;
} else {
platform_needed--;
j++;
}
}
return max_platforms;
}
const arrivals = [900, 940, 950, 1100, 1500, 1800];
const departures = [910, 1200, 1120, 1130, 1900, 2000];
console.log(findPlatform(arrivals, departures));JavaScript's default sort() converts numbers to strings and sorts lexicographically, so 1000 comes before 900, causing incorrect order and wrong platform count.
function minPlatforms(arr, dep) {
arr.sort((a, b) => a - b);
dep.sort((a, b) => a - b);
let i = 0, j = 0, platform_needed = 0, max_platforms = 0;
while (i < arr.length && j < dep.length) {
if (arr[i] < dep[j]) {
platform_needed++;
if (platform_needed > max_platforms) max_platforms = platform_needed;
i++;
} else {
platform_needed--;
j++;
}
}
return max_platforms;
}
const arrivals = [1000, 1010, 1025, 1030, 1040];
const departures = [1015, 1020, 1035, 1045, 1050];
console.log(minPlatforms(arrivals, departures));The maximum number of trains overlapping is 4, so 4 platforms are needed.
Sorting arrival and departure times separately lets us move through both lists in order, comparing times to find overlaps efficiently.
