FastPrepMinimum Station Tracks for a Train Schedule

Minimum Station Tracks for a Train Schedule

BNSF Railway logoBNSF Railway● MediumFULLTIMEONSITE INTERVIEW

Problem statement

A station has a schedule of trains. Each trains[i] = [arrival, departure] gives the minute a train arrives and the minute it leaves. While a train is in the station it needs a track of its own.

  • A train holds its track from arrival up to, but not including, departure.
  • A track freed at minute t can take a train that arrives at minute t.
  • Any train can use any track.

Return the smallest number of tracks that lets every train on the schedule stop at the station.

Function

minTracks(trains: int[][]) → int

Examples

Example 1

trains = [[540,600],[555,620],[610,700],[615,640]]return = 3

From minute 555 to 600 the first two trains are both in the station, and from 615 to 620 the trains [555,620], [610,700] and [615,640] are all there at once. Three tracks are needed.

Example 2

trains = [[100,200],[200,300],[300,400]]return = 1

Each train arrives exactly when the previous one leaves. A track that is freed at minute 200 can take the train arriving at minute 200, so one track is enough.

Example 3

trains = [[0,50],[10,20],[30,40],[45,60]]return = 2

The long train [0,50] holds one track. The other three trains never overlap each other: [10,20] leaves before [30,40] arrives, which leaves before [45,60] arrives. They can share a second track, so the answer is 2.

Constraints

  • 1 <= trains.length <= 2000
  • trains[i].length == 2
  • 0 <= arrival < departure <= 10^6

More BNSF Railway problems

See BNSF Railway hiring insights
Saved
public int minTracks(int[][] trains) {
    // Write your code here.
}
Checking account…