DSA Factory
Free Mixed sets lessonsMixed sets · Stage 0 · Set 1 · Step 4

Trains at the station

Find the most trains in the station at once by sorting arrivals and departures separately and sweeping along time. About 12 minutes.

Two sorted lists, one sweep

A station gets trains, each with an arrival time and a departure time. How many platforms are needed so that no train waits? That equals the most trains in the station at the same moment.

The pairs don't matter once you think of it as a story over time: at each arrival the count goes up, at each departure it goes down. So sort all the arrival times in one list and all the departure times in another, and walk through time, always handling whichever event is earlier.

Arrival: adds a train to the station.
Departure: removes a train.
In code
arrivals.sort()
departures.sort()
here = best = 0
i = j = 0
Arrivals sorted: 1, 2, 4. Departures sorted: 3, 5, 6. How many trains at once?
012
arrivals
1
2
4
departures
3
5
6
most
1
trains
1

Time 1: a train arrives. One in the station.

Move 1 of 5

Ties go to the arrival

What if one train arrives at exactly the moment another leaves? In this problem they overlap for that instant, so the arriving train needs a platform before the departing one frees up. Count the arrival first when times are equal.

In the code that means comparing with "less than or equal" when you choose between the next arrival and the next departure.

Equal times: count the arrival before the departure.
Quick check

A train arrives at time 5 and another leaves at time 5. Do they need separate platforms?

  1. AYes, because both are there at time 5
  2. BNo, one platform is freed just in time
  3. CIt depends on how long each train stays
Show the answer

Yes, because both are there at time 5. In this problem a train that leaves at the moment another arrives still counts as present.

Your problem

Platforms needed

arrivals[i] and departures[i] are the arrival and departure times of train i, where arrivals[i] ≤ departures[i]. A train is in the station from its arrival time to its departure time, including both times. Return the smallest number of platforms needed so that no train has to wait.

Example
arrivals = [1, 2, 4], departures = [3, 5, 6] → 2

0 ≤ trains ≤ 100,000 · 0 ≤ time ≤ 1,000,000,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve