GRDY-P4

Fewest platforms

Practice 4 of 6Greedy algorithms8 tests

The problem

Each train is a pair (arrive, depart) with arrive < depart: it is in the station from arrive up to, but not including, depart. A platform can hold one train at a time. Return the fewest platforms that are enough for all the trains.

platforms([(0, 4), (1, 3), (2, 6), (3, 5),
           (5, 8), (6, 9), (7, 10)])
# 3: at time 2, three trains are in at once

Times are half-open, as in Python slices: (s, e) includes s but not e. So a train that ends at 5 and one that starts at 5 do not overlap.

That is, a platform is free again the moment its train leaves. The trains can come in any order. Return 0 for an empty list.

Limits

  • Up to 200,000 trains. Aim for O(n log n).

Builds on GRDY-3 Interval scheduling.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

8 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2No trainsNot run
3One trainNot run
4Leaves as the next arrivesNot run
5All at onceNot run
6Not sortedNot run
7A long stayNot run
8200,000 trainsNot run