Skip to content
Related Articles

Related Articles

Improve Article

Minimum Number of Platforms Required for a Railway/Bus Station

  • Difficulty Level : Medium
  • Last Updated : 04 May, 2021

Given the 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 that represent the 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 
Explanation: 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 
Explanation: Only one platform is needed. 

Naive Solution: 



  • Approach: The idea is to take every interval one by one and find the number of intervals that overlap with it. Keep track of the maximum number of intervals that overlap with an interval. Finally, return the maximum value.
  • Algorithm: 
    1. Run two nested loops the outer loop from start to end and the inner loop from i+1 to end.
    2. For every iteration of the outer loop find the count of intervals that intersect with the current interval.
    3. Update the answer with the maximum count of overlap in each iteration of the outer loop.
    4. Print the answer.

Implementation: 

CPP14




// Program to find minimum number of platforms
// required on a railway station
#include <algorithm>
#include <iostream>
 
using namespace std;
 
// Returns minimum number of platforms reqquired
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 = 1, j = 0;
 
    // run a nested  loop to find overlap
    for (int i = 0; i < n; i++) {
        // minimum platform
        plat_needed = 1;
 
        for (int j = i + 1; j < n; j++) {
            // check for overlap
            if ((arr[i] >= arr[j] && arr[i] <= dep[j]) ||
           (arr[j] >= arr[i] && arr[j] <= dep[i]))
                plat_needed++;
        }
 
        // update result
        result = max(result, plat_needed);
    }
 
    return result;
}
 
// Driver Code
int main()
{
    int arr[] = { 900, 940, 950, 1100, 1500, 1800 };
    int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Minimum Number of Platforms Required = "
         << findPlatform(arr, dep, n);
    return 0;
}

Java




// Program to find minimum number of platforms
// required on a railway station
import java.io.*;
 
class GFG {
    // Returns minimum number of platforms reqquired
    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 = 1, j = 0;
 
        // run a nested  loop to find overlap
        for (i = 0; i < n; i++) {
            // minimum platform
            plat_needed = 1;
 
            for (j = i + 1; j < n; j++) {
                // check for overlap
                if ((arr[i] >= arr[j] && arr[i] <= dep[j])
                    || (arr[j] >= arr[i]
                        && arr[j] <= dep[i]))
                    plat_needed++;
            }
 
            // update result
            result = Math.max(result, plat_needed);
        }
 
        return result;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 900, 940, 950, 1100, 1500, 1800 };
        int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 };
        int n = 6;
        System.out.println(
            "Minimum Number of Platforms Required = "
            + findPlatform(arr, dep, n));
    }
}

Javascript




<script>
// Program to find minimum number of platforms
// required on a railway station
 
function max(a,b)
{
    if(a==b)
         return a;
    else{
        if(a>b)
            return a;
        else
            return b;
       }
}
 
// Returns minimum number of platforms reqquired
function findPlatform( arr, dep, n)
{
 
    // plat_needed indicates number of platforms
    // needed at a time
    var plat_needed = 1, result = 1;
    var i = 1, j = 0;
 
    // run a nested loop to find overlap
    for (var i = 0; i < n; i++) {
        // minimum platform
        plat_needed = 1;
 
        for (var j = i + 1; j < n; j++) {
            // check for overlap
            if ((arr[i] >= arr[j] && arr[i] <= dep[j]) ||
        (arr[j] >= arr[i] && arr[j] <= dep[i]))
                plat_needed++;
        }
 
        // update result
        result = max(result, plat_needed);
    }
 
    return result;
}
 
var arr = [ 900, 940, 950, 1100, 1500, 1800 ];
    var dep = [ 910, 1200, 1120, 1130, 1900, 2000 ];
    var n =6;
    document.write("Minimum Number of Platforms Required = "
        +findPlatform(arr, dep, n));
 
 
</script>
Output
Minimum Number of Platforms Required = 3

Complexity Analysis: 

  • Time Complexity: O(n^2). 
    Two nested loops traverse the array, so the time complexity is O(n^2).
  • Space Complexity: O(1). 
    As no extra space is required.

Efficient Solution:

  • Approach: The idea is to consider all events in sorted order. Once the events are in sorted order, trace the number of trains at any time keeping track of trains that have arrived, but not departed.

For example, consider the above example. 

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}

All events are sorted by time.
Total platforms at any time can be obtained by
subtracting total departures from total arrivals
by that time.

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

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

Note: This approach assumes that trains are arriving and departing on the same date. 
 

Algorithm:

  1. Sort the arrival and departure times of trains.
  2. Create two pointers i=0, and j=0 and a variable to store ans and current count plat
  3. Run a loop while i<n and j<n and compare the ith element of arrival array and jth element of departure array.
  4. If the arrival time is less than or equal to departure then one more platform is needed so increase the count, i.e. plat++ and increment i
  5. Else if the arrival time greater than departure then one less platform is needed so decrease the count, i.e. plat– and increment j
  6. Update the ans, i.e ans = max(ans, plat).

Implementation: This doesn’t create a single sorted list of all events, rather it individually sorts arr[] and dep[] arrays, and then uses the merge process of merge sort to process them together as a single sorted array. 

C++




// Program to find minimum number of platforms
// required on a railway station
#include <algorithm>
#include <iostream>
 
using namespace std;
 
// Returns minimum number of platforms reqquired
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[] = { 900, 940, 950, 1100, 1500, 1800 };
    int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Minimum Number of Platforms Required = "
         << findPlatform(arr, dep, n);
    return 0;
}

Java




// Program to find minimum number of platforms
 
import java.util.*;
 
class GFG {
 
    // Returns minimum number of platforms reqquired
    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[] = { 900, 940, 950, 1100, 1500, 1800 };
        int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 };
        int n = arr.length;
        System.out.println("Minimum Number of Platforms Required = "
                           + findPlatform(arr, dep, n));
    }
}

Python3




# Program to find minimum
# number of platforms
# required on a railway
# station
 
# Returns minimum number
# of platforms reqquired
 
 
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
 
# Driver code
 
 
arr = [900, 940, 950, 1100, 1500, 1800]
dep = [910, 1200, 1120, 1130, 1900, 2000]
n = len(arr)
 
print("Minimum Number of Platforms Required = ",
      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
    // reqquired
    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 = { 900, 940, 950, 1100, 1500, 1800 };
        int[] dep = { 910, 1200, 1120, 1130, 1900, 2000 };
        int n = arr.Length;
        Console.Write("Minimum Number of "
                      + " Platforms Required = "
                      + findPlatform(arr, dep, n));
    }
}
 
// This code os contributed by nitin mittal.

PHP




<?php
// PHP Program to find minimum number
// of platforms  required on a railway
// station
 
// Returns minimum number of
// platforms reqquired
function findPlatform($arr, $dep, $n)
{
     
    // Sort arrival and
    // departure arrays
    sort($arr);
    sort($dep);
     
    // 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++;
            $i++;
        }
     
        // Else decrement count
        // of platforms needed
        elseif ($arr[$i] > $dep[$j])
        {
            $plat_needed--;
            $j++;
        }
 
        // Update result if needed
        if ($plat_needed > $result)
            $result = $plat_needed;
    }
     
    return $result;
}
 
    // Driver Code
    $arr = array(900, 940, 950, 1100, 1500, 1800);
    $dep = array(910, 1200, 1120, 1130, 1900, 2000);
    $n = count($arr);
    echo "Minimum Number of Platforms Required = ", findPlatform($arr, $dep, $n);
 
// This code is contributed by anuj_67.
?>

Javascript




<script>
// Javascript Program to find minimum number
// of platforms  required on a railway
// station
 
// Returns minimum number of
// platforms reqquired
function findPlatform(arr, dep, n)
{
     
    // Sort arrival and
    // departure arrays
    arr = arr.sort();
    dep = dep.sort();
     
    // plat_needed indicates
    // number of platforms
    // needed at a time
    let plat_needed = 1;
    let result = 1;
    let i = 1;
    let 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 = new Array(900, 940, 950, 1100, 1500, 1800);
    let dep = new Array(910, 1200, 1120, 1130, 1900, 2000);
    let n = arr.length;
    document.write("Minimum Number of Platforms Required = " + findPlatform(arr, dep, n));
 
// This code is contributed by Saurabh Jaiswal.
</script>
Output
Minimum Number of Platforms Required = 3

Complexity Analysis: 

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

Note: The solution mentioned above uses O(n log n) time complexity and O(1) Space Complexity. There is one more approach to the problem which uses O(n) extra space and O(n) time to solve the problem: 
Minimum Number of Platforms Required for a Railway/Bus Station | Set 2 (Map-based approach)
This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :