Home
DSA Visualizer
Greedy Algorithms
Minimum Platforms
Minimum Platforms
The Minimum Platforms problem asks for the fewest platforms a railway station needs, given the arrival and departure times of all trains, so that no train is kept waiting.
READY
T1
T2
T3
T4
T5
T6
ARRIVE
DEPART
In use
0
Platforms
0
6 trains through one station, and the only question is how many are standing there at once.
Next
Sort the arrivals, and sort the departures. Nothing pairs the two lists up.
Timetable
Intuition
Imagine you are the station master. A platform is needed for every train currently at the station. If a new train arrives while all platforms are occupied, you need another platform.
To find the minimum platforms required, you just need to know the maximum number of trains present at the station at the same time.
Concept
The Greedy Approach (sorting events):
- Treat all arrival and departure times as independent events on a timeline.
- Sort these events by time. When an arrival and a departure share a time, count the arrival first: a train arriving at the same minute another leaves still needs its own platform, which is what the
arr[i] ≤ dep[j]comparison below encodes. If your problem treats a departure as freeing the platform at that minute, change it to<. - Iterate through time:
- Arrival: platform_needed++
- Departure: platform_needed--
- Track the maximum value of
platform_neededreached.
How it Works
- Sort: Sort the array of Arrival times and Departure times separately.
- Two Pointers: Use pointer
ifor Arrival andjfor Departure. - Iterate: Compare
arr[i]anddep[j]:- If
arr[i] ≤ dep[j]: A train arrived. Incrplatforms. Updatemax. Incri. - If
arr[i] > dep[j]: A train left. Decrplatforms. Incrj.
- If
- Result: The maximum count recorded.
Step-by-Step Breakdown
Trains: T1[9:00-9:10], T2[9:40-12:00], T3[9:50-11:20]
- Sort Arrivals: 900, 940, 950.
- Sort Departures: 910, 1120, 1200.
- Comparison:
- 900 (Arr) ≤ 910 (Dep)? Yes. Plat=1. Max=1. Next Arr (940).
- 940 (Arr) ≤ 910 (Dep)? No. (Wait, 940 > 910... strict ordering logic)
- Actually compare current Arr vs current Dep pointers.
- Arr(940) > Dep(910)? Yes. Train left. Plat=0. Next Dep (1120).
- Wait, logic:
Arr[i] vs Dep[j].
900 vs 910: Arrive. P=1. i=1.
940 vs 910: Depart. P=0. j=1. (Logic check: 940 > 910 means departure happened BEFORE next arrival). - Correct trace:
Events: 900(A), 910(D), 940(A), 950(A), 1120(D), 1200(D).
900(A): P=1.
910(D): P=0.
940(A): P=1.
950(A): P=2. Max=2.
...
When to Use
- Railway station management.
- Calculating maximum simultaneous resource usage (e.g., server load, meeting rooms).
When NOT to Use
- When resources are not identical or interchangeable (e.g., specific track types).
How to Identify
Keywords: "Minimum platforms", "Maximum intersection", "Overlapping intervals".
Sample Problems
Applying for software engineering roles? Free, no sign-up:
