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.

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

python
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

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.

06

Complexity

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