Minimum number of platforms required for a railway

Pattern: Intervals greedy

medium

Sort the arrival times and the departure times separately and sweep them like a merge: an arrival adds a train, a departure removes one, and the most trains at once is the number of platforms. An arrival at the same time as a departure still needs its own platform.

The problem

Given the arrival and departure times of trains on one day, return the fewest platforms needed so that no train waits. A train that arrives at the same time as another departs needs a separate platform. The example above gives 3.

Think first

  • What number are you really looking for?
  • Do you need to know which departure belongs to which train?
  • At equal times, which event comes first?

Hints

    Brute force, and why it fails

    For each train, count the trains whose stay overlaps its arrival: O(n²).

    The key insight

    Sorting arrivals and departures separately turns the timeline into two sorted lists that can be merged in one sweep.

    Dry run

    in0

    arr [900, 940, 950, 1100, 1500, 1800], dep [910, 1200, 1120, 1130, 1900, 2000]. Sorted dep: 910, 1120, 1130, 1200, 1900, 2000.

    Step 1 of 4

    The plan

    sort arr; sort dep; i = j = 0
    while i < n:
        if arr[i] <= dep[j]: in += 1; best = max(best, in); i += 1
        else: in -= 1; j += 1
    

    Complexity

    Time
    O(n log n)
    Space
    O(n)

    Two sorts and a linear sweep.

    Edge cases

    • One train: 1.
    • Arrival equal to a departure: counted as overlapping.
    • All trains at once: n.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int findPlatform(int[] arr, int[] dep) {
            int[] a = arr.clone(), d = dep.clone();
            Arrays.sort(a);
            Arrays.sort(d);
            int i = 0, j = 0, inStation = 0, best = 0;
            while (i < a.length) {
                if (a[i] <= d[j]) {                 // the next event is an arrival (a train arriving as one leaves still needs a platform)
                    inStation++;
                    best = Math.max(best, inStation);
                    i++;
                } else {                            // the next event is a departure
                    inStation--;
                    j++;
                }
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int findPlatform(vector<int>& arr, vector<int>& dep) {
            vector<int> a(arr), d(dep);
            sort(a.begin(), a.end());
            sort(d.begin(), d.end());
            size_t i = 0, j = 0;
            int inStation = 0, best = 0;
            while (i < a.size()) {
                if (a[i] <= d[j]) {                 // an arrival (arriving as one leaves still needs a platform)
                    inStation++;
                    best = max(best, inStation);
                    i++;
                } else {                            // a departure
                    inStation--;
                    j++;
                }
            }
            return best;
        }
    };

    Python

    class Solution:
        def findPlatform(self, arr: list[int], dep: list[int]) -> int:
            a, d = sorted(arr), sorted(dep)
            i = j = in_station = best = 0
            while i < len(a):
                if a[i] <= d[j]:                    # an arrival (arriving as one leaves still needs a platform)
                    in_station += 1
                    best = max(best, in_station)
                    i += 1
                else:                               # a departure
                    in_station -= 1
                    j += 1
            return best

    Common mistakes

    • Using < and sharing a platform at equal times.
    • Sorting the pairs together and losing the merge.

    Similar problems