Minimum Number of Platforms Required for a Railway/Bus Station

Given arrival and departure times of all trains that reach a railway station, the task is to find the minimum number of platforms required for the railway station so that no train waits. We are given two arrays which represent arrival and departure times of trains that stop.

Examples:

Input: arr[] = {9:00, 9:40, 9:50, 11:00, 15:00, 18:00} dep[] = {9:10, 12:00, 11:20, 11:30, 19:00, 20:00} Output: 3 Explantion: There are at-most three trains at a time (time between 11:00 to 11:20)

Input: arr[] = {9:00, 9:40} dep[] = {9:10, 12:00} Output: 1 Explantion: Only one platform is needed.

class Solution {
    public int minPlatforms(int[] arrival, int[] departure) {
        int count = 0;
        Arrays.sort(arrival);
        Arrays.sort(departure);
        int i = 0, j = 0, max = 0;
        while (i < arrival.length && j < departure.length) {
            if (arrival[i] < departure[i]) {
                i++;
                count++;
            } else {
                j++;
                count--;
            }
            max = Math.max(max, count);
        }
        return max;
    }
}

Last updated