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.

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 inner loop from i+1 to end.
    2. For every iteration of outer loop find the count of intervals that intersect with the current interval.
    3. Update the answer with maximum count of overlap in each iteration of outer loop.
    4. Print the answer.
  • Implementation:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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 program to test methods of graph class
    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;
    }

    chevron_right

    
    

    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 time 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 merge process of merge sort to process them together as a single sorted array.

    C++

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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 program to test methods of graph class
    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;
    }

    chevron_right

    
    

    Java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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 program to test methods of graph class
        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));
        }
    }

    chevron_right

    
    

    Python3

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <div id="highlighter_997400" class="syntaxhighlighter nogutter  "><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="comments"># Program to find minimum </code></div><div class="line number2 index1 alt1"><code class="comments"># number of platforms  </code></div><div class="line number3 index2 alt2"><code class="comments"># required on a railway </code></div><div class="line number4 index3 alt1"><code class="comments"># station </code></div><div class="line number5 index4 alt2"><code class="undefined spaces"> </code> </div><div class="line number6 index5 alt1"><code class="comments"># Returns minimum number </code></div><div class="line number7 index6 alt2"><code class="comments"># of platforms reqquired </code></div><div class="line number8 index7 alt1"><code class="keyword">def</code> <code class="plain">findPlatform(arr, dep, n): </code></div><div class="line number9 index8 alt2"><code class="undefined spaces"> </code> </div><div class="line number10 index9 alt1"><code class="undefined spaces">    </code><code class="comments"># Sort arrival and </code></div><div class="line number11 index10 alt2"><code class="undefined spaces">    </code><code class="comments"># departure arrays </code></div><div class="line number12 index11 alt1"><code class="undefined spaces">    </code><code class="plain">arr.sort() </code></div><div class="line number13 index12 alt2"><code class="undefined spaces">    </code><code class="plain">dep.sort() </code></div><div class="line number14 index13 alt1"><code class="undefined spaces">  </code> </div><div class="line number15 index14 alt2"><code class="undefined spaces">    </code><code class="comments"># plat_needed indicates </code></div><div class="line number16 index15 alt1"><code class="undefined spaces">    </code><code class="comments"># number of platforms </code></div><div class="line number17 index16 alt2"><code class="undefined spaces">    </code><code class="comments"># needed at a time </code></div><div class="line number18 index17 alt1"><code class="undefined spaces">    </code><code class="plain">plat_needed </code><code class="keyword">=</code> <code class="value">1</code></div><div class="line number19 index18 alt2"><code class="undefined spaces">    </code><code class="plain">result </code><code class="keyword">=</code> <code class="value">1</code></div><div class="line number20 index19 alt1"><code class="undefined spaces">    </code><code class="plain">i </code><code class="keyword">=</code> <code class="value">1</code></div><div class="line number21 index20 alt2"><code class="undefined spaces">    </code><code class="plain">j </code><code class="keyword">=</code> <code class="value">0</code></div><div class="line number22 index21 alt1"><code class="undefined spaces">  </code> </div><div class="line number23 index22 alt2"><code class="undefined spaces">    </code><code class="comments"># Similar to merge in </code></div><div class="line number24 index23 alt1"><code class="undefined spaces">    </code><code class="comments"># merge sort to process  </code></div><div class="line number25 index24 alt2"><code class="undefined spaces">    </code><code class="comments"># all events in sorted order </code></div><div class="line number26 index25 alt1"><code class="undefined spaces">    </code><code class="keyword">while</code> <code class="plain">(i < n </code><code class="keyword">and</code> <code class="plain">j < n): </code></div><div class="line number27 index26 alt2"><code class="undefined spaces">    </code> </div><div class="line number28 index27 alt1"><code class="undefined spaces">        </code><code class="comments"># If next event in sorted </code></div><div class="line number29 index28 alt2"><code class="undefined spaces">        </code><code class="comments"># order is arrival,  </code></div><div class="line number30 index29 alt1"><code class="undefined spaces">        </code><code class="comments"># increment count of </code></div><div class="line number31 index30 alt2"><code class="undefined spaces">        </code><code class="comments"># platforms needed </code></div><div class="line number32 index31 alt1"><code class="undefined spaces">        </code><code class="keyword">if</code> <code class="plain">(arr[i] <</code><code class="keyword">=</code> <code class="plain">dep[j]): </code></div><div class="line number33 index32 alt2"><code class="undefined spaces">         </code> </div><div class="line number34 index33 alt1"><code class="undefined spaces">            </code><code class="plain">plat_needed</code><code class="keyword">+</code><code class="keyword">=</code> <code class="value">1</code></div><div class="line number35 index34 alt2"><code class="undefined spaces">            </code><code class="plain">i</code><code class="keyword">+</code><code class="keyword">=</code> <code class="value">1</code></div><div class="line number36 index35 alt1"><code class="undefined spaces">         </code> </div><div class="line number37 index36 alt2"><code class="undefined spaces">  </code> </div><div class="line number38 index37 alt1"><code class="undefined spaces">        </code><code class="comments"># Else decrement count </code></div><div class="line number39 index38 alt2"><code class="undefined spaces">        </code><code class="comments"># of platforms needed </code></div><div class="line number40 index39 alt1"><code class="undefined spaces">        </code><code class="keyword">elif</code> <code class="plain">(arr[i] > dep[j]): </code></div><div class="line number41 index40 alt2"><code class="undefined spaces">         </code> </div><div class="line number42 index41 alt1"><code class="undefined spaces">            </code><code class="plain">plat_needed</code><code class="keyword">-</code><code class="keyword">=</code> <code class="value">1</code></div><div class="line number43 index42 alt2"><code class="undefined spaces">            </code><code class="plain">j</code><code class="keyword">+</code><code class="keyword">=</code> <code class="value">1</code></div><div class="line number44 index43 alt1"><code class="undefined spaces"> </code> </div><div class="line number45 index44 alt2"><code class="undefined spaces">        </code><code class="comments"># Update result if needed  </code></div><div class="line number46 index45 alt1"><code class="undefined spaces">        </code><code class="keyword">if</code> <code class="plain">(plat_needed > result):  </code></div><div class="line number47 index46 alt2"><code class="undefined spaces">            </code><code class="plain">result </code><code class="keyword">=</code> <code class="plain">plat_needed </code></div><div class="line number48 index47 alt1"><code class="undefined spaces">         </code> </div><div class="line number49 index48 alt2"><code class="undefined spaces">    </code><code class="keyword">return</code> <code class="plain">result </code></div><div class="line number50 index49 alt1"><code class="undefined spaces"> </code> </div><div class="line number51 index50 alt2"><code class="comments"># driver code </code></div><div class="line number52 index51 alt1"><code class="undefined spaces"> </code> </div><div class="line number53 index52 alt2"><code class="plain">arr </code><code class="keyword">=</code> <code class="plain">[</code><code class="value">900</code><code class="plain">, </code><code class="value">940</code><code class="plain">, </code><code class="value">950</code><code class="plain">, </code><code class="value">1100</code><code class="plain">, </code><code class="value">1500</code><code class="plain">, </code><code class="value">1800</code><code class="plain">] </code></div><div class="line number54 index53 alt1"><code class="plain">dep </code><code class="keyword">=</code> <code class="plain">[</code><code class="value">910</code><code class="plain">, </code><code class="value">1200</code><code class="plain">, </code><code class="value">1120</code><code class="plain">, </code><code class="value">1130</code><code class="plain">, </code><code class="value">1900</code><code class="plain">, </code><code class="value">2000</code><code class="plain">] </code></div><div class="line number55 index54 alt2"><code class="plain">n </code><code class="keyword">=</code> <code class="functions">len</code><code class="plain">(arr) </code></div><div class="line number56 index55 alt1"><code class="undefined spaces"> </code> </div><div class="line number57 index56 alt2"><code class="functions">print</code><code class="plain">(</code><code class="string">"Minimum Number of Platforms Required = "</code><code class="plain">, </code></div><div class="line number58 index57 alt1"><code class="undefined spaces">        </code><code class="plain">findPlatform(arr, dep, n)) </code></div><div class="line number59 index58 alt2"><code class="undefined spaces"> </code> </div><div class="line number60 index59 alt1"><code class="comments"># This code is contributed </code></div><div class="line number61 index60 alt2"><code class="comments"># by Anant Agarwal. </code></div></div></td></tr></tbody></table></div>

    chevron_right

    
    

    C#

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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 program to test methods of
        // graph class
        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.

    chevron_right

    
    

    PHP

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?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.
    ?>

    chevron_right

    
    


    Output:

    Minimum Number of Platforms Required = 3
  • Complexity Analysis:

    • Time Complexity: O(nlogn).
      One traversal O(n) of both the array is needed after sorting O(nlogn), so the time Complexity is O(nlogn).
    • 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.




My Personal Notes arrow_drop_up