Algorithms · Visualized
Minimum Platforms
Greedy
Make the locally optimal choice at each step, hoping it leads to a globally optimal solution.
Given train arrival and departure times, find the minimum number of platforms needed so no train has to wait. Time: O(n log n) average, O(n log n) worst; space: O(1) extra, or O(n) if sorting isn't in place.
Big-O: Works when the problem has optimal substructure + greedy-choice property — e.g. intervals, Huffman, fractional knapsack.
Minimum Platforms
GreedyGiven train arrival and departure times, find the minimum number of platforms needed so no train has to wait. The greedy idea: sort arrivals and departures separately, then sweep through time — every arrival needs a platform (increment count), every departure frees one (decrement count), and the peak count reached is the answer.
How Minimum Platforms Works
- Sort the arrival times array and the departure times array independently.
- Use two pointers, one for arrivals and one for departures, plus counters for 'platforms currently in use' and 'maximum platforms needed'.
- Compare the current arrival time and current departure time.
- If the next arrival happens before (or at the same time as) the next departure, a new platform is needed: increment the current count and move the arrival pointer forward, updating the maximum if this is a new peak.
- Otherwise, a platform is freed: decrement the current count and move the departure pointer forward. Continue until all arrivals are processed.
Minimum Platforms Worked Example
Input: {arrivals: [900, 940, 950, 1100, 1500, 1800], departures: [910, 1200, 1120, 1130, 1900, 2000]}
Sorted arrivals & departures as given. Process: 900 arrives (count=1,max=1). 910 departs before 940 arrives (count=0). 940 arrives (count=1). 950 arrives before 1120 departs (count=2,max=2). 1100 arrives before 1120 departs (count=3,max=3). 1120 departs (count=2). 1130 departs (count=1). 1200 departs (count=0). 1500 arrives (count=1). 1800 arrives before 1900 departs (count=2,max stays3). Minimum platforms required: 3.
def minimum_platforms(arr, dep):
arr.sort()
dep.sort()
i = j = 0
need = platforms = 0
while i < len(arr):
if arr[i] <= dep[j]:
need += 1
platforms = max(platforms, need)
i += 1
else:
need -= 1
j += 1
return platformsBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Minimum Platforms Time & Space Complexity
When to Use Minimum Platforms
- Railway/airport scheduling to determine the minimum infrastructure (platforms, gates) needed.
- Same underlying pattern as Meeting Rooms II — finding peak concurrent overlap.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.