The Wayback Machine - https://web.archive.org/web/20241231234148/https://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/
Open In App

Minimum Platforms Required for Given Arrival and Departure Times

Last Updated : 02 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We are given two arrays that represent the arrival and departure times of trains, the task is to find the minimum number of platforms required so that no train waits.

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 
Explanation: There are at-most three trains at a time (time between 9:40 to 12:00)

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

[Naive Approach] Using Two Nested Loops – O(N^2) time and O(1) auxiliary space

The basic idea is to iterating over each train’s arrival and departure time and comparing it with all other trains to determine if there is an overlap. Essentially, for each train, we check how many other trains are occupying the platforms simultaneously.

To implement this,

  • we have to use two nested loops where the outer loop picks each train one by one and the inner loop checks for overlaps with the remaining trains.
  • If the arrival time of a train is between the arrival and departure times of another train, it is considered as an overlap and a counter is incremented.
  • After checking all the trains, the maximum value of the counter gives the number of platforms needed.

Code implementation:

C++14
// C++ program to implement the above approach
#include <bits/stdc++.h>
using namespace std;

// Function to find the minimum number of platforms
// required
int findPlatform(int arr[], int dep[], int n)
{
    // plat_needed indicates number of platforms
    // needed at a time
    int plat_needed = 1, result = 1;

    // Run a nested for-loop to find the overlap
    for (int i = 0; i < n; i++) {

        // Initially one platform is needed
        plat_needed = 1;
        for (int j = 0; j < n; j++) {
            if (i != j)
                // Increment plat_needed when there is an
                // overlap
                if (arr[i] >= arr[j] && dep[j] >= arr[i])
                    plat_needed++;
        }

        // Update the result
        result = max(plat_needed, result);
    }
    return result;
}

// Driver Code
int main()
{

    // Train 1 => Arrival : 01:00, Departure : 09:00
    // Train 2 => Arrival : 03:00, Departure : 04:00
    // Train 3 => Arrival : 05:00, Departure : 06:00
    int arr[] = { 100, 300, 500 };
    int dep[] = { 900, 400, 600 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findPlatform(arr, dep, n);
    return 0;
}

// Code contributed by farzams101
Java
// Program to find minimum number of platforms
// required on a railway station
import java.io.*;

class GFG {
    // Returns minimum number of platforms required
    public static int findPlatform(int arr[], int dep[],
                                   int n)
    {

        // plat_needed indicates number of platforms
        // needed at a time
        int plat_needed = 1, result = 1;

        // run a nested  loop to find overlap
        for (int i = 0; i < n; i++) {
            // minimum platform
            plat_needed = 1;

            for (int j = 0; j < n; j++) {
                if (i != j)
                    // check for overlap
                    if (arr[i] >= arr[j]
                        && dep[j] >= arr[i])
                        plat_needed++;
            }

            // update result
            result = Math.max(result, plat_needed);
        }

        return result;
    }

    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 100, 300, 500 };
        int dep[] = { 900, 400, 600 };
        int n = 3;
        System.out.println(findPlatform(arr, dep, n));
    }
}
Python
# Program to find minimum number of platforms
# required on a railway station


def findPlatform(arr, dep, n):
    # plat_needed indicates number of platforms
    # needed at a time
    plat_needed = 1
    result = 1

    # run a nested loop to find overlap
    for i in range(n):
        # minimum platform needed
        plat_needed = 1

        for j in range(n):
            # check for overlap
            if i != j:
                if (arr[i] >= arr[j] and dep[j] >= arr[i]):
                    plat_needed += 1

        # update result
        result = max(result, plat_needed)

    return result

# Driver code
def main():
    arr = [100, 300, 500]
    dep = [900, 400, 600]

    n = len(arr)

    print("{}".format(
        findPlatform(arr, dep, n)))


if __name__ == '__main__':
    main()
C#
// Program to find minimum number of platforms
// required on a railway station

using System;

public class GFG {

    // Returns minimum number of platforms required
    public static int findPlatform(int[] arr, int[] dep,
                                   int n)
    {

        // plat_needed indicates number of platforms
        // needed at a time
        int plat_needed = 1, result = 1;
        int i = 0, j = 0;

        // run a nested  loop to find overlap
        for (i = 0; i < n; i++) {
            // minimum platform
            plat_needed = 1;

            for (j = 0; j < n; j++) {
                if (i != j)
                    // check for overlap
                    if (arr[i] >= arr[j]
                        && dep[j] >= arr[i])
                        plat_needed++;
            }

            // update result
            result = Math.Max(result, plat_needed);
        }

        return result;
    }

    // Driver Code

    static public void Main()
    {

        int[] arr = { 100, 300, 500 };
        int[] dep = { 900, 400, 600 };
        int n = 3;
        Console.WriteLine(findPlatform(arr, dep, n));
    }
}
JavaScript
// Function to find the minimum number of platforms required
function findPlatform(arr, dep, n) {
    // plat_needed indicates number of platforms needed at a time
    let plat_needed = 1;
    let result = 1;

    // Run a nested loop to find the overlap
    for (let i = 0; i < n; i++) {
        // Initially one platform is needed
        plat_needed = 1;
        for (let j = 0; j < n; j++) {
            if (i !== j) {
                // Increment plat_needed when there is an overlap
                if (arr[i] >= arr[j] && dep[j] >= arr[i]) {
                    plat_needed++;
                }
            }
        }

        // Update the result
        result = Math.max(plat_needed, result);
    }

    return result;
}

// Driver Code
// Train 1 => Arrival : 01:00, Departure : 09:00
// Train 2 => Arrival : 03:00, Departure : 04:00
// Train 3 => Arrival : 05:00, Departure : 06:00
let arr = [100, 300, 500];
let dep = [900, 400, 600];
let n = arr.length;
console.log(findPlatform(arr, dep, n));

Output
2

Time Complexity: O(n2), Two nested loops traverse the array.
Auxiliary space: O(1), As no extra space is required.  

[Expected Approach] Using Sorting and Two Pointers – O(n log(n)) time and O(1) auxiliary space

This approach uses sorting and two-pointer to reduce the complexity. First, we sort the arrival and departure times of all trains. Then, using two pointers, we traverse through both arrays.

The idea is to maintain a count of platforms needed at any point in time.

Time      Event Type      Total Platforms Needed at this Time
9:00Arrival1
9:10Departure 0
9:40Arrival1
9:50Arrival2
11:00Arrival3
11:20Departure 2
11:30Departure 1
12:00Departure 0
15:00Arrival1
18:00Arrival2
19:00Departure 1
20:00Departure 0

Minimum Platforms needed on railway station = Maximum platforms needed at any time = 3

To implement this approach:

  • Start by pointing both pointers to the beginning of the arrival and departure arrays.
  • If the current arrival time is less than or equal to the current departure time, it means a new platform is needed, so we have to increment the platform count and move the arrival pointer forward.
  • If the current arrival time is greater than the current departure time, it means a train has left, freeing up a platform, so we decrement the platform count and move the departure pointer forward.
  • The maximum value of platforms needed at any point during this traversal gives the required number of platforms.

Code Implementation:

C++
// Program to find minimum number of platforms
// required on a railway station
#include <bits/stdc++.h>
using namespace std;

// Returns minimum number of platforms required
int findPlatform(int arr[], int dep[], int n)
{
    // Sort arrival and departure arrays
    sort(arr, arr + n);
    sort(dep, dep + n);

    // plat_needed indicates number of platforms
    // needed at a time
    int plat_needed = 1, result = 1;
    int i = 1, j = 0;

    // Similar to merge in merge sort to process
    // all events in sorted order
    while (i < n && j < n) {
        // If next event in sorted order is arrival,
        // increment count of platforms needed
        if (arr[i] <= dep[j]) {
            plat_needed++;
            i++;
        }

        // Else decrement count of platforms needed
        else if (arr[i] > dep[j]) {
            plat_needed--;
            j++;
        }

        // Update result if needed
        if (plat_needed > result)
            result = plat_needed;
    }

    return result;
}

// Driver code
int main()
{

    int arr[] = { 100, 300, 500 };
    int dep[] = { 900, 400, 600 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findPlatform(arr, dep, n);
    return 0;
}
Java
// Program to find minimum number of platforms

import java.util.*;

class GFG {

    // Returns minimum number of platforms required
    static int findPlatform(int arr[], int dep[], int n)
    {
        // Sort arrival and departure arrays
        Arrays.sort(arr);
        Arrays.sort(dep);

        // plat_needed indicates number of platforms
        // needed at a time
        int plat_needed = 1, result = 1;
        int i = 1, j = 0;

        // Similar to merge in merge sort to process
        // all events in sorted order
        while (i < n && j < n) {
            // If next event in sorted order is arrival,
            // increment count of platforms needed
            if (arr[i] <= dep[j]) {
                plat_needed++;
                i++;
            }

            // Else decrement count of platforms needed
            else if (arr[i] > dep[j]) {
                plat_needed--;
                j++;
            }

            // Update result if needed
            if (plat_needed > result)
                result = plat_needed;
        }

        return result;
    }

    // Driver code
    public static void main(String[] args)
    {

        int arr[] = { 100, 300, 500 };
        int dep[] = { 900, 400, 600 };
        int n = arr.length;
        System.out.println(findPlatform(arr, dep, n));
    }
}
Python
# Program to find minimum
# number of platforms
# required on a railway
# station

# Returns minimum number
# of platforms required


def findPlatform(arr, dep, n):

    # Sort arrival and
    # departure arrays
    arr.sort()
    dep.sort()

    # plat_needed indicates
    # number of platforms
    # needed at a time
    plat_needed = 1
    result = 1
    i = 1
    j = 0

    # Similar to merge in
    # merge sort to process
    # all events in sorted order
    while (i < n and j < n):

        # If next event in sorted
        # order is arrival,
        # increment count of
        # platforms needed
        if (arr[i] <= dep[j]):

            plat_needed += 1
            i += 1

        # Else decrement count
        # of platforms needed
        elif (arr[i] > dep[j]):

            plat_needed -= 1
            j += 1

        # Update result if needed
        if (plat_needed > result):
            result = plat_needed

    return result


arr = [100, 300, 500]
dep = [900, 400, 600]
n = len(arr)

print(findPlatform(arr, dep, n))

# This code is contributed
# by Anant Agarwal.
C#
// C# program to find minimum number
// of platforms
using System;

class GFG {

    // Returns minimum number of platforms
    // required
    static int findPlatform(int[] arr, int[] dep, int n)
    {

        // Sort arrival and departure arrays
        Array.Sort(arr);
        Array.Sort(dep);

        // plat_needed indicates number of
        // platforms needed at a time
        int plat_needed = 1, result = 1;
        int i = 1, j = 0;

        // Similar to merge in merge sort
        // to process all events in sorted
        // order
        while (i < n && j < n) {

            // If next event in sorted order
            // is arrival, increment count
            // of platforms needed
            if (arr[i] <= dep[j]) {
                plat_needed++;
                i++;
            }

            // Else decrement count of
            // platforms needed
            else if (arr[i] > dep[j]) {
                plat_needed--;
                j++;
            }

            // Update result if needed
            if (plat_needed > result)
                result = plat_needed;
        }

        return result;
    }

    // Driver code
    public static void Main()
    {

        int[] arr = { 100, 300, 500 };
        int[] dep = { 900, 400, 600 };
        int n = arr.Length;
        Console.Write(findPlatform(arr, dep, n));
    }
}

// This code os contributed by nitin mittal.
JavaScript
// Function to find the minimum number of platforms required
function findPlatform(arr, dep, n) {
    // Sort arrival and departure arrays
    arr.sort((a, b) => a - b);
    dep.sort((a, b) => a - b);

    // plat_needed indicates number of platforms needed at a time
    let plat_needed = 1, result = 1;
    let i = 1, j = 0;

    // Similar to merge in merge sort to process all events in sorted order
    while (i < n && j < n) {
        // If next event in sorted order is arrival, increment count of platforms needed
        if (arr[i] <= dep[j]) {
            plat_needed++;
            i++;
        } 
        // Else decrement count of platforms needed
        else if (arr[i] > dep[j]) {
            plat_needed--;
            j++;
        }

        // Update result if needed
        if (plat_needed > result) {
            result = plat_needed;
        }
    }

    return result;
}

// Driver Code
let arr = [100, 300, 500];
let dep = [900, 400, 600 ];
let n = arr.length;
console.log(findPlatform(arr, dep, n));

Output
3

Time Complexity: O(N * log N), One traversal O(n) of both the array is needed after sorting O(N * log N).
Auxiliary space: O(1), As no extra space is required.

[Efficient for Large Arrays and Small Max Time] O(n + maxTime) time and O(maxTime) space

The sweep line algorithm is an efficient method for solving problems involving intervals or segment. The idea is to convert the arrival time and departure time of each train in the form of (x, y) coordinate, and then apply the sweep line algorithm to finding the maximum number of overlap at any time.

To implement this approach:

  • First, create an array of size greater than maximum Departure time to track the number of platforms needed at each time point of time.
  • Iterate over the arrival and departure times: for each arrival time, do v[arrival time] += 1 and for each departure time, do v[departure time + 1] -= 1.
  • This process effectively marks the times when platforms are occupied and when they are free.
  • After updating the array, we calculate the cumulative sum of this array to find the maximum number of platforms needed at any time.
  • This maximum value represents the minimum number of platforms required.

Code Implementation:

C++
// C++ program to implement the above approach
#include <bits/stdc++.h>
using namespace std;

// Function to find the minimum number of platforms
// required
int findPlatformOptimized(int arr[], int dep[], int n)
{
    int count = 0, maxPlatforms = 0;
  
    // Find the maximum departure time
    int maxDepartureTime = dep[0];
    for (int i = 1; i < n; i++) {
        maxDepartureTime = max(maxDepartureTime, dep[i]);
    }

    // Create a vector to store the count of trains at each
    // time
    vector<int> v(maxDepartureTime + 2, 0);

    // Increment the count at the arrival time and decrement
    // at the departure time
    for (int i = 0; i < n; i++) {
        v[arr[i]]++;
        v[dep[i] + 1]--;
    }

    // Iterate over the vector and keep track of the maximum
    // sum seen so far
    for (int i = 0; i <= maxDepartureTime + 1; i++) {
        count += v[i];
        maxPlatforms = max(maxPlatforms, count);
    }

    return maxPlatforms;
}

// Driver Code
int main()
{
    int arr[] = { 100, 300, 600 };
    int dep[] = { 900, 400, 500 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findPlatformOptimized(arr, dep, n);
    return 0;
}
Java
import java.util.*;

public class Main {
    // Function to find the minimum number of platforms required
    public static int findPlatformOptimized(int[] arr, int[] dep, int n)
    {
        int count = 0, maxPlatforms = 0;
        // Find the maximum departure time
        int maxDepartureTime = dep[0];
        for (int i = 1; i < n; i++) {
            maxDepartureTime = Math.max(maxDepartureTime, dep[i]);
        }

        // Create a vector to store the count of trains at each time
        List<Integer> v = new ArrayList<>(maxDepartureTime + 2);
        for (int i = 0; i < maxDepartureTime + 2; i++) {
            v.add(0);
        }

        // Increment the count at the arrival time and decrement at the departure time
        for (int i = 0; i < n; i++) {
            v.set(arr[i], v.get(arr[i]) + 1);
            v.set(dep[i] + 1, v.get(dep[i] + 1) - 1);
        }

        // Iterate over the vector and keep track of the maximum sum seen so far
        for (int i = 0; i <= maxDepartureTime + 1; i++) {
            count += v.get(i);
            maxPlatforms = Math.max(maxPlatforms, count);
        }

        return maxPlatforms;
    }

    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 100, 300, 600 };
        int[] dep = { 900, 400, 500 };
        int n = arr.length;
        System.out.println(findPlatformOptimized(arr, dep, n));
    }
}
Python
from typing import List

# Function to find the minimum number of platforms required.
def find_platform_optimized(arr: List[int], dep: List[int], n: int) -> int:

    count = 0
    max_platforms = 0

    # Find the maximum departure time
    max_departure_time = max(dep)

    # Create a list to store the count of trains at each time
    v = [0] * (max_departure_time + 2)

    # Increment the count at the arrival time and decrement at the departure time
    for i in range(n):
        v[arr[i]] += 1
        v[dep[i] + 1] -= 1

    # Iterate over the list and keep track of the maximum sum seen so far
    for i in range(max_departure_time + 2):
        count += v[i]
        max_platforms = max(max_platforms, count)

    return max_platforms

# Driver Code
if __name__ == '__main__':
    arr = [100, 300, 600]
    dep = [900, 400, 500]
    n = len(arr)
    print(find_platform_optimized(arr, dep, n))
C#
using System;
using System.Collections.Generic;

class Program {
    static int FindPlatformOptimized(int[] arr, int[] dep,
                                     int n)
    {
        int count = 0, maxPlatforms = 0;
        // Find the maximum departure time
        int maxDepartureTime = dep[0];
        for (int i = 1; i < n; i++) {
            maxDepartureTime
                = Math.Max(maxDepartureTime, dep[i]);
        }

        // Create a list to store the count of trains at
        // each time
        List<int> v = new List<int>(maxDepartureTime + 2);
        for (int i = 0; i <= maxDepartureTime + 1; i++) {
            v.Add(0);
        }

        // Increment the count at the arrival time and
        // decrement at the departure time
        for (int i = 0; i < n; i++) {
            v[arr[i]]++;
            v[dep[i] + 1]--;
        }

        // Iterate over the list and keep track of the
        // maximum sum seen so far
        for (int i = 0; i <= maxDepartureTime + 1; i++) {
            count += v[i];
            maxPlatforms = Math.Max(maxPlatforms, count);
        }

        return maxPlatforms;
    }

    static void Main(string[] args)
    {
        int[] arr = { 100, 300, 600 };
        int[] dep = { 900, 400, 500 };
        int n = arr.Length;
        Console.WriteLine(
            FindPlatformOptimized(arr, dep, n));
    }
}
// This code is contributed by sarojmcy2e
JavaScript
// Function to find the minimum number of platforms
// required
function findPlatformOptimized(arr, dep, n) {
    let count = 0, maxPlatforms = 0;
    // Find the maximum departure time
    let maxDepartureTime = dep[0];
    for (let i = 1; i < n; i++) {
        maxDepartureTime = Math.max(maxDepartureTime, dep[i]);
    }

    // Create an array to store the count of trains at each
    // time
    const v = new Array(maxDepartureTime + 2).fill(0);

    // Increment the count at the arrival time and decrement
    // at the departure time
    for (let i = 0; i < n; i++) {
        v[arr[i]]++;
        v[dep[i] + 1]--;
    }

    // Iterate over the array and keep track of the maximum
    // sum seen so far
    for (let i = 0; i <= maxDepartureTime + 1; i++) {
        count += v[i];
        maxPlatforms = Math.max(maxPlatforms, count);
    }

    return maxPlatforms;
}

// Driver Code
const arr = [100, 300, 600];
const dep = [900, 400, 500];
const n = arr.length;
console.log(findPlatformOptimized(arr, dep, n));

Output
2

Time Complexity: O(n), where n is the number of trains. The algorithm iterates over the input arrays once to update the vector, and then iterates over the vector once to calculate the cumulative sum. Both iterations take O(n) time. Please note that we assume that the maximum departure time would be a constant. In general, we can say time complexity is O(n + maxDepartureTime)
Auxiliary space: O(maxDepartureTime), as we create a vector of size maxDepartureTime+2 to store the count of trains at each time.



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg