GeeksforGeeks Medium

Minimum Number of Platforms

Given train arrival and departure times, find the minimum platforms so no train waits.

greedysortingtwo-pointers
Open on GeeksforGeeks ↗
02

Intuition

The answer is the maximum number of trains present at once. Sort arrivals and departures separately and sweep: an arrival is +1 platform, a departure is −1. The peak of that running count is the answer.

How to spot this pattern

The key move is refusing to think in trains and thinking in events instead. Sorting arrivals and departures independently breaks the pairing — which is fine, because the peak occupancy doesn't care which train is which, only how many are inside at once. Any "maximum concurrent X" problem yields to this sweep: +1 on each start, −1 on each end, track the running peak.

03

Approach

1

Separate the two event streams

Platform need only changes at an arrival or a departure — sort each list and merge-walk them chronologically.

2

Sweep with a counter

If the next arrival is ≤ the next departure, a train arrives before any leaves: need += 1. Otherwise one leaves: need -= 1. Track the max.

3

Why ≤ matters

If a train arrives exactly when another departs, both briefly need platforms — count the arrival first.

04

Solution & live demo

1def min_platforms(arr, dep):
2 arr.sort(); dep.sort()
3 i = j = need = best = 0
4 while i < len(arr):
5 if arr[i] <= dep[j]:
6 need += 1; i += 1
7 else:
8 need -= 1; j += 1
9 best = max(best, need)
10 return best
05

Common pitfalls

Keeping arrival and departure paired

✗ Wrong
trains = sorted(zip(arr, dep))
for a, d in trains: ...
✓ Right
arr.sort(); dep.sort()
while i < len(arr):
    if arr[i] <= dep[j]: need += 1; i += 1
    else:                need -= 1; j += 1

Keeping pairs forces you to ask which specific train left, which needs a heap or a scan. Sorting the two lists separately turns the problem into a merge of timestamps — the only question left is whether the next event is an arrival or a departure.

Using < and freeing the platform too early

✗ Wrong
if arr[i] < dep[j]:
✓ Right
if arr[i] <= dep[j]:

A train arriving at the exact minute another departs cannot reuse the platform — both occupy it at that instant. Strict < treats the slot as already free and undercounts by one on touching times.

Recording the peak only at the end

✗ Wrong
while i < len(arr):
    ...
return need
✓ Right
    ...
    best = max(best, need)
return best

need is the current occupancy, which falls back toward zero as trains leave. The answer is the highest it ever reached, so the maximum must be sampled after every arrival.

06

Edge cases

Arrival equals a departure time

Tie processed as arrival first → correctly demands an extra platform.

All trains overlap

Counter climbs to n and never drops until the end.

07

Complexity

Time
O(n log n)
Space
O(1)
Two sorts + linear merge sweep.