Open In App

Minimum Number of Platforms Required for a Railway/Bus Station | Set 2 (Set based approach)

Last Updated : 02 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given the arrival and departure times of all trains that reach a railway station, find the minimum number of platforms required for the railway station so that no train waits. We are given two arrays that 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
There are at-most three trains at a time 
(time between 11:00 to 11:20)
Recommended Practice

We have already discussed its simple and sorting based solutions in below post. 
Minimum Number of Platforms Required for a Railway/Bus Station.

In this post, we are inserting all the arrival and departure times in a multiset. The first value of element in multiset tells the arrival/departure time and second value tells whether it’s arrival or departure represented by ‘a’ or ‘d’ respectively. 

If its arrival then do increment by 1 otherwise decrease value by 1. If we are taking the input from STDIN then we can directly insert the times in the multiset and no need to store the times in the array. 

Implementation:

C++




// C++ program to find minimum number of platforms
// required on a railway station
#include <bits/stdc++.h>
using namespace std;
 
int findPlatform(int arr[], int dep[], int n)
{
    // Insert all the times (arr. and dep.)
    // in the multiset.
    multiset<pair<int, char> > order;
    for (int i = 0; i < n; i++) {
 
        // If its arrival then second value
        // of pair is 'a' else 'd'
        order.insert(make_pair(arr[i], 'a'));
        order.insert(make_pair(dep[i], 'd'));
    }
 
    int result = 0;
    int plat_needed = 0;
 
    // Start iterating the multiset.
    for (auto it : order) {
 
        // If its 'a' then add 1 to plat_needed
        // else minus 1 from plat_needed.
        if (it.second == 'a')
            plat_needed++;
        else
            plat_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




// Java program to find minimum number
// of platforms required on a railway station
import java.io.*;
import java.util.*;
 
class pair
{
    int first;
    char second;
     
    pair(int key1, char key2)
    {
        this.first = key1;
        this.second = key2;
    }
}
 
class GFG{
     
public static int findPlatform(int arr[], int dep[],
                               int n)
{
     
    // Insert all the times (arr. and dep.)
    // in the ArrayList of pairs.
    ArrayList<pair> order = new ArrayList<>();
    for(int i = 0; i < n; i++)
    {
        order.add(new pair(arr[i], 'a'));
        order.add(new pair(dep[i], 'd'));
    }
 
    // Custom sort order ArrayList, first
    // by time than by arrival or departure
    Collections.sort(order, new Comparator<pair>()
    {
        public int compare(pair p1, pair p2)
        {
            if (p1.first == p2.first)
                return new Character(p1.second)
                    .compareTo(
                        new Character(p2.second));
                         
            return p1.first - p2.first;
        }
    });
     
    int result = 1;
    int plat_needed = 0;
     
    for(int i = 0; i < order.size(); i++)
    {
        pair p = order.get(i);
         
        // If its 'a' then add 1 to plat_needed
        // else minus 1 from plat_needed.
        if (p.second == 'a')
            plat_needed++;
        else
            plat_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 = 6;
     
    System.out.println("Minimum Number of " +
                       "Platforms Required = " +
                       findPlatform(arr, dep, n));
}
}
 
// This code is contributed by RohitOberoi


Python3




# Python3 program to find minimum number
# of platforms required on a railway station
def findPlatform(arr, dep, n):
     
    # Inserting all the arr. and dep. times
    # in the array times
    times = []
    for i in range(n):
        times.append([dep[i], 'd'])
        times.append([arr[i], 'a'])
         
    # Sort the array
    times = sorted(times, key = lambda x: x[1])
    times = sorted(times, key = lambda x: x[0])
     
    result, plat_needed = 0, 0
 
    for i in range(2 * n):
         
        # If its 'a' then add 1 to plat_needed
        # else minus 1 from plat_needed.
        if times[i][1] == 'a':
            plat_needed += 1
            result = max(plat_needed, result)
        else:
            plat_needed -= 1
     
    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 Tharun Reddy


C#




// C# program to find minimum number
// of platforms required on a railway station
using System;
using System.Collections.Generic;
 
public class pair {
  public int first;
  public char second;
 
  public pair(int key1, char key2) {
    this.first = key1;
    this.second = key2;
  }
}
 
public class GFG {
 
  public static int findPlatform(int []arr, int []dep, int n) {
 
    // Insert all the times (arr. and dep.)
    // in the List of pairs.
    List<pair> order = new List<pair>();
    for (int i = 0; i < n; i++) {
      order.Add(new pair(arr[i], 'a'));
      order.Add(new pair(dep[i], 'd'));
    }
 
    // Custom sort order List, first
    // by time than by arrival or departure
    order.Sort((p1,p2)=> p1.first == p2.first? p1.second -
               p2.second:  p1.first - p2.first);
 
    int result = 1;
    int plat_needed = 0;
 
    for (int i = 0; i < order.Count; i++) {
      pair p = order[i];
 
      // If its 'a' then add 1 to plat_needed
      // else minus 1 from plat_needed.
      if (p.second == 'a')
        plat_needed++;
      else
        plat_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 = 6;
 
    Console.WriteLine("Minimum Number of " +
                      "Platforms Required = " +
                      findPlatform(arr, dep, n));
  }
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
    // JavaScript program to find minimum number of platforms
    // required on a railway station
 
    const findPlatform = (arr, dep, n) => {
        // Insert all the times (arr. and dep.)
        // in the multiset.
        let order = new Set();
        for (let i = 0; i < n; i++) {
 
            // If its arrival then second value
            // of pair is 'a' else 'd'
            order.add([arr[i], 'a']);
            order.add([dep[i], 'd']);
        }
 
        let result = 0;
        let plat_needed = 0;
        order = [...order];
 
        order = order.sort((a, b) => a[0] - b[0])
        // Start iterating the multiset.
        for (let it in order) {
 
            // If its 'a' then add 1 to plat_needed
            // else minus 1 from plat_needed.
            if (order[it][1] == 'a')
                plat_needed++;
            else
                plat_needed--;
 
            if (plat_needed > result)
                result = plat_needed;
 
        }
        return result;
    }
 
    // Driver code
 
    let arr = [900, 940, 950, 1100, 1500, 1800];
    let dep = [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 rakeshsahni
 
</script>


Output

Minimum Number of Platforms Required = 3

Complexity Analysis:  

  • Time Complexity: O( N* LogN).

           Since we are inserting into multiset and it maintain elements in sorted order. So N insert operations in multiset requires N*LogN time complexity. 

  • Space Complexity: O(N).  

           We are using multiset which will have 2*N elements .

Using constant space and O(n) time complexity

All the trains will arrive and depart in only one day, i.e. a 24-hour time frame, hence we can use an array and for every arrival increase the value at that time (time in 24-hour format), and for every departure decrement the value at the index. In the array, every index denotes time in 24hr format and the sum of traversal up to that index is the number of platforms required, at that time.

Illustration:

arrivals – { 1200 , 1230 , 1240 , 1245}
departures – { 1210 , 1245 , 1250 , 1250}
make an array of size 2361 having 0 as the default value .
for the above example the array will have the following values – 1 ,-1 , 1 , -1 , 0 , -2
at indices – 1200 , 1210 , 1230 ,1240 ,1245,1250
Rest all indices have the default value of 0,in the above situation the number of platforms required at different times are –
platforms     time
   1             1200
   2             1210
   3             1230
   2             1240
   2             1245
   1             1250
3 is the max so 3 is the answer

Approach:

Follow the below steps to solve the problem:

  1. Make an array for 24 hrs i.e. – 2361 size , named time.
  2. Now for every arrival increment the element at the index in the array time.
  3. For every departure decrement the element (default integer value in time is 0).
  4. Then traverse the entire array and keep adding the value at current index to a variable count. 
  5. The max value of the variable count is the answer.

Implementation:

C++




// C++ program to find minimum number of platforms
// required on a railway station
#include <bits/stdc++.h>
using namespace std;
 
int minPlatform(int arrival[], int departure[], int n)
{
 
    // as time range from 0 to 2359 in 24 hour clock,
    // we declare an array for values from 0 to 2360
    int platform[2361] = {0};
    int requiredPlatform = 1;
    for (int i = 0; i < n; i++) {
 
        // increment the platforms for arrival
        ++platform[arrival[i]];
 
         // once train departs we decrease the platform count
        --platform[departure[i] + 1];
    }
 
    // We are running loop till 2361 because maximum time value
    // in a day can be 23:60
    for (int i = 1; i < 2361; i++) {
 
        // taking cumulative sum of platform give us required
        // number of platform for every minute
        platform[i] = platform[i] + platform[i - 1];
        requiredPlatform = max(requiredPlatform, platform[i]);
    }
    return requiredPlatform;
}
 
// 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 = "
         << minPlatform(arr, dep, n);
    return 0;
}


Java




// Java program to find minimum number
// of platforms required on a railway
// station
import java.util.*;
import java.lang.*;
 
class GFG{
 
static int minPlatform(int arrival[],
                       int departure[],
                       int n)
{
     
    // As time range from 0 to 2359 in
    // 24 hour clock, we declare an array
    // for values from 0 to 2360
    int[] platform = new int[2361];
    int requiredPlatform = 1;
     
    for(int i = 0; i < n; i++)
    {
         
        // Increment the platforms for arrival
        ++platform[arrival[i]];
 
         // Once train departs we decrease
         // the platform count
        --platform[departure[i] + 1];
    }
     
    // We are running loop till 2361 because
    // maximum time value in a day can be 23:60
    for(int i = 1; i < 2361; i++)
    {
         
        // Taking cumulative sum of platform
        // give us required number of
        // platform for every minute
        platform[i] = platform[i] +
                      platform[i - 1];
        requiredPlatform = Math.max(requiredPlatform,
                                    platform[i]);
    }
    return requiredPlatform;
}
 
// 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 = " +
                       minPlatform(arr, dep, n));
}
}
 
// This code is contributed by offbeat


Python3




# Python3 program to find minimum number
# of platforms required on a railway station
def minPlatform(arrival, departure, n):
 
    # As time range from 0 to 2359 in
    # 24 hour clock, we declare an array
    # for values from 0 to 2360
    platform = [0] * 2361
    requiredPlatform = 1
     
    for i in range(n):
 
        # Increment the platforms for arrival
        platform[arrival[i]] += 1
 
        # Once train departs we decrease the
        # platform count
        platform[departure[i] + 1] -= 1
 
    # We are running loop till 2361 because
    # maximum time value in a day can be 23:60
    for i in range(1, 2361):
 
        # Taking cumulative sum of
        # platform give us required
        # number of platform for every minute
        platform[i] = platform[i] + platform[i - 1]
        requiredPlatform = max(requiredPlatform,
                               platform[i])
         
    return requiredPlatform
 
# 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 = ",
       minPlatform(arr, dep, n))
 
# This code is contributed by PawanJain1


C#




// C# program to find minimum number
// of platforms required on a railway
// station
using System;
class GFG {
     
    static int minPlatform(int[] arrival, int[] departure, int n)
    {
        // As time range from 0 to 2359 in
        // 24 hour clock, we declare an array
        // for values from 0 to 2360
        int[] platform = new int[2361];
        int requiredPlatform = 1;
          
        for(int i = 0; i < n; i++)
        {
              
            // Increment the platforms for arrival
            ++platform[arrival[i]];
      
             // Once train departs we decrease
             // the platform count
            --platform[departure[i] + 1];
        }
          
        // We are running loop till 2361 because
        // maximum time value in a day can be 23:60
        for(int i = 1; i < 2361; i++)
        {
              
            // Taking cumulative sum of platform
            // give us required number of
            // platform for every minute
            platform[i] = platform[i] +
                          platform[i - 1];
            requiredPlatform = Math.Max(requiredPlatform,
                                        platform[i]);
        }
        return requiredPlatform;
    }
 
  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 = " +
                       minPlatform(arr, dep, n));
  }
}
 
// This code is contributed by divyesh072019.


Javascript




<script>
 
        // JavaScript program for the above approach
 
        function minPlatform(arrival, departure, n) {
 
            // as time range from 0 to 2359 in 24 hour clock,
            // we declare an array for values from 0 to 2360
            let platform = new Array(2361).fill(0);
            let requiredPlatform = 1;
            for (let i = 0; i < n; i++) {
 
                // increment the platforms for arrival
                ++platform[arrival[i]];
 
                // once train departs we
                // decrease the platform count
                --platform[departure[i] + 1];
            }
 
            // We are running loop till 2361
            // because maximum time value
            // in a day can be 23:60
            for (let i = 1; i < 2361; i++) {
 
                // taking cumulative sum of
                // platform give us required
                // number of platform for every minute
                platform[i] =
                platform[i] + platform[i - 1];
                 
                requiredPlatform =
                Math.max(requiredPlatform, platform[i]);
            }
            return requiredPlatform;
        }
 
        // Driver code
 
        let arr = [900, 940, 950, 1100, 1500, 1800];
        let dep = [910, 1200, 1120, 1130, 1900, 2000];
        let n = arr.length;
        document.write("Minimum Number of Platforms Required = "
            + minPlatform(arr, dep, n));
 
 
    // This code is contributed by Potta Lokesh
 
    </script>


Output

Minimum Number of Platforms Required = 3

Complexity Analysis:  

  • Time Complexity: O(N).
  • Space Complexity: O(1).  

 



Similar Reads

Minimum Number of Platforms Required for a Railway/Bus Station
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}, d
28 min read
Minimum total cost incurred to reach the last station
Given an array where each element denotes the number of chocolates corresponding to each station and to move from station i to station i+1, we get A[i] - A[i+1] chocolates for free, if this number is negative, we lose that many chocolates also. You can only move from station i to station i+1, if we have non-negative number of chocolates. Given the
7 min read
Number of stopping station problem
There are 12 intermediate stations between two places A and B. Find the number of ways in which a train can be made to stop at 4 of these intermediate stations so that no two stopping stations are consecutive?Examples - Input : n = 12, s = 4Output : 126 Input : n = 16, s = 5Output : 792 Explanation 1 : Fix/remove of the four stops as fixed points a
6 min read
Python Program for Number of stopping station problem
There are 12 intermediate stations between two places A and B. Find the number of ways in which a train can be made to stop at 4 of these intermediate stations so that no two stopping stations are consecutive? Examples - Input : n = 12, s = 4 Output : 126 Input : n = 16, s = 5 Output : 792 # Python code to calculate number # of ways of selecting \'
1 min read
Minimum increment or decrement required to sort the array | Top-down Approach
Given an array arr[] of N integers, the task is to sort the array in increasing order by performing a minimum number of operations. In a single operation, an element of the array can either be incremented or decremented by 1. Print the minimum number of operations required.Examples: Input: arr[] = {5, 4, 3, 2, 1} Output: 6 Explanation: The sorted a
13 min read
Minimum number of candies required to distribute among children based on given conditions
Given an array arr[] consisting of N positive integers representing the ratings of N children, the task is to find the minimum number of candies required for distributing to N children such that every child gets at least one candy and the children having the higher rating get more candies than its neighbours. Examples: Input: arr[] = {1, 0, 2}Outpu
13 min read
Find maximum distance between any city and station
Given the number of cities n numbered from 0 to n-1 and the cities in which stations are located, the task is to find the maximum distance between any city and its nearest station. Note that the cities with stations can be given in any order. Examples: Input: numOfCities = 6, stations = [1, 4] Output: 1 Input: numOfCities = 6, stations = [3] Output
7 min read
Railway Station | TCS CodeVita 2020
Given an integer N, representing the number of stations lying between the source and the destination. There are three trains available from every station and their stoppage patterns are as follows: Train 1: Stops at every stationTrain 2: Stops at every alternate stationTrain 3: Stops at every third station The task is to find the number of ways to
12 min read
Count ways to reach the Nth station
Given N stations and three trains A, B, and C such that train A stops at every station, train B stops at every second station, and train C stops at every third station, the task is to find the number of ways to reach the Nth station can be reached from station 1. Examples: Input: N = 4Output: 3Explanation:Below are the ways of reaching station 4 fr
8 min read
Queue based approach for first non-repeating character in a stream
Given a stream of characters and we have to find first non repeating character each time a character is inserted to the stream. Examples: Input : a a b c Output : a -1 b b Input : a a c Output : a -1 cRecommended PracticeFirst non-repeating character in a streamTry It! We have already discussed a Doubly linked list based approach in the previous po
5 min read