AlgoTales · Roadmap

Minimum platforms

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Minimum platforms counts the most things happening at the same time, such as trains at a station or meetings in a building. That peak number is how many platforms, rooms or servers you must have to never turn anyone away.

Practical use cases

  • Web app: How many meeting rooms does the office need. A workplace app has a day of meetings with start and end times. Sorting all starts and ends together and counting up and down finds the busiest moment, say 7 meetings at 11 am, so the office needs 7 rooms.
  • Web app: Cloud server capacity for jobs. A SaaS scheduler runs reports with start and end times. The peak count of overlapping jobs tells how many worker servers to keep, so you neither overpay nor queue jobs. The company spends only on the servers it needs at the busiest moment, and the rest of the time they can be switched off.
  • Web app: Hotel room demand forecast. A booking dashboard shows check-in and check-out dates. The highest number of guests staying on one night tells the manager the room count needed for that season. The manager can set the room count and price for the busy night correctly, and fill the quiet nights with offers.
  • System: Railway stations and airport gates. Station and airport planners use this count to decide how many platforms or gates avoid waiting aircraft or trains. In each case the answer is the peak number of things happening at once, found by counting arrivals up and departures down along a sorted timeline.

The story: Platforms at the Little Station

Mira's town was getting a new railway station, and the engineer, Mr. Iyer, was worried. "If I build too few platforms, trains will wait outside in the sun. If I build too many, the money is wasted."

He had the timetable with six trains: one arrives at 9:00 and leaves at 9:10, another arrives at 9:40 and stays until 12:00, and so on. Mr. Iyer tried drawing a picture for every minute of the day. His notebook ran out of pages.

Mira noticed something: "You do not need to know which train leaves. You only need to know how many trains are inside at any moment." She wrote all the arrival times in a sorted list and all the departure times in another sorted list. Then she walked through time: whenever an arrival comes first, one more platform is busy; whenever a departure comes first, one is freed.

The busiest moment was 3 trains at once (between 11:00 and 11:20). So three platforms were enough. This is the minimum platforms problem. It is greedy in the sense that we simply handle whichever event comes first and keep the highest count we ever see.

How to spot this problem, and where you need it

You have many events with start and end times and need to know the smallest number of rooms, machines or platforms that can host them all without anyone waiting.

Signs you need it

  • The question is "minimum number of rooms, servers, platforms or gates" or "maximum overlap at one moment".
  • Events can overlap in complicated ways, and you want one number for capacity planning.
  • You are tempted to check every event against every other one to see overlaps.

Where to use it in a project

  • Capacity planners for meeting rooms, servers, workers and hotel rooms.
  • Transport timetable tools that decide platform or gate counts.

The solution

Put all start times in one sorted list and all end times in another. Walk through both with two pointers: if the next start is before the next end, one more resource is in use, so add one; otherwise one is freed, so subtract one. Track the largest value reached. That peak is the minimum number of platforms needed.

Payoff: Before: guessing 12 rooms and wasting money. After: a quick count shows the true peak of 7 rooms.

Explain it like I am 8

Count how many kids are inside the bouncy castle at the same time. Every time a kid goes in, add one. Every time a kid comes out, subtract one. The most kids ever inside together is how big the castle must be.

How it works, step by step

  1. Sort the arrival times and, separately, sort the departure times.
  2. Use two pointers: one on the next arrival, one on the next departure.
  3. If the next arrival is before or at the next departure, a train comes in: add 1 to the platforms in use.
  4. Otherwise a train leaves: subtract 1.
  5. After every change, remember the largest count. That is the answer.

The code in four languages

PHP

<?php
// arr[i] and dep[i] are the arrival and departure times of train i (as numbers like 930).
function minPlatforms(array $arr, array $dep): int {
    sort($arr);                       // sorted arrivals
    sort($dep);                       // sorted departures (pairing does not matter)
    $n = count($arr);
    $i = 0; $j = 0;
    $inStation = 0; $best = 0;
    while ($i < $n) {
        if ($arr[$i] <= $dep[$j]) {   // next event is an arrival
            $inStation++;
            $best = max($best, $inStation);
            $i++;
        } else {                      // next event is a departure
            $inStation--;
            $j++;
        }
    }
    return $best;
}

echo minPlatforms([900, 940, 950, 1100, 1500, 1800], [910, 1200, 1120, 1130, 1900, 2000]);   // 3

JavaScript

// arr[i] and dep[i] are the arrival and departure times of train i (as numbers like 930).
function minPlatforms(arr, dep) {
  arr = [...arr].sort((a, b) => a - b);   // sorted arrivals
  dep = [...dep].sort((a, b) => a - b);   // sorted departures (pairing does not matter)
  const n = arr.length;
  let i = 0, j = 0;
  let inStation = 0, best = 0;
  while (i < n) {
    if (arr[i] <= dep[j]) {               // next event is an arrival
      inStation++;
      best = Math.max(best, inStation);
      i++;
    } else {                              // next event is a departure
      inStation--;
      j++;
    }
  }
  return best;
}

console.log(minPlatforms([900, 940, 950, 1100, 1500, 1800], [910, 1200, 1120, 1130, 1900, 2000]));   // 3

Java

import java.util.*;

public class Main {
    // arr[i] and dep[i] are the arrival and departure times of train i (as numbers like 930).
    static int minPlatforms(int[] arrivals, int[] departures) {
        int[] arr = arrivals.clone();
        int[] dep = departures.clone();
        Arrays.sort(arr);                 // sorted arrivals
        Arrays.sort(dep);                 // sorted departures (pairing does not matter)
        int n = arr.length;
        int i = 0, j = 0;
        int inStation = 0, best = 0;
        while (i < n) {
            if (arr[i] <= dep[j]) {       // next event is an arrival
                inStation++;
                best = Math.max(best, inStation);
                i++;
            } else {                      // next event is a departure
                inStation--;
                j++;
            }
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(minPlatforms(new int[]{900, 940, 950, 1100, 1500, 1800},
                                        new int[]{910, 1200, 1120, 1130, 1900, 2000}));   // 3
    }
}

Go

package main

import (
	"fmt"
	"slices"
)

// minPlatforms: arrivals[i] and departures[i] are the times of train i (as numbers like 930).
func minPlatforms(arrivals, departures []int) int {
	arr := slices.Clone(arrivals)
	dep := slices.Clone(departures)
	slices.Sort(arr) // sorted arrivals
	slices.Sort(dep) // sorted departures (pairing does not matter)
	n := len(arr)
	i, j := 0, 0
	inStation, best := 0, 0
	for i < n {
		if arr[i] <= dep[j] { // next event is an arrival
			inStation++
			best = max(best, inStation)
			i++
		} else { // next event is a departure
			inStation--
			j++
		}
	}
	return best
}

func main() {
	fmt.Println(minPlatforms([]int{900, 940, 950, 1100, 1500, 1800}, []int{910, 1200, 1120, 1130, 1900, 2000})) // 3
}

Time: O(n log n) · Extra space: O(1). Two sorts, then one walk through the events. Apart from the sorted copies, only a few counters are kept.

Watch out for

  • Thinking you must keep each train's own arrival and departure paired. Sorted separately works, because only the count matters.
  • Using < instead of <= when an arrival and a departure have the same time. The arriving train still needs its own platform, so the arrival goes first.
  • Forgetting to remember the maximum and returning the final count (which is usually smaller).

Quick check

  1. What do we sort?
    • Only departures
    • Arrivals and departures, separately
    • Trains by their length of stay
  2. What is the answer at the end?
    • The final count of trains
    • Number of trains
    • The largest count seen at any moment
  3. A train arrives at the exact minute another leaves. How many platforms does that moment need?
    • Two, they overlap at that instant
    • One, the platform is reused
    • Zero