DEV Community

Discussion on: Minimum Number of Platforms Required for a Railway Station, Bloomberg Interview question. 🚄🚄🚄

Collapse
 
majaleksander profile image
Aleksander Maj

I always appreciate interesting coding challenges during the interview, here is my solution using some light functional methods:

const arr = [900, 940, 950, 1100, 1500, 1800];
const dept = [910, 1200, 1120, 1130, 1900, 2000];

const numPlatforms = (arrivals, departures) => (
  [
  ...arrivals.map(time => ({time, value: 1})), 
  ...departures.map(time => ({time, value: -1}))
  ].
  sort((a,b) => (a.time - b.time)).
  reduce((acc, s) => ({
    value: (acc.value + s.value),
    max: Math.max(acc.max, acc.value)
  }), {value: 0, max: 0}).
  max
);

numPlatforms(arr, dept);
Collapse
 
akhilpokle profile image
Akhil

Hi ! thanks for your solution. Could you explain the flow of execution? I am not that well versed in javascript methods.

Collapse
 
majaleksander profile image
Aleksander Maj
  1. It merges an array of arrivals with departures and adds some values (1 when the train arrives and -1 when it departures). Result of it should be an array of sth like:
    [{time: 9:00, value: 1}, ....,{time: 2000, value: -1}]

  2. Then I sort it like you did it.

  3. .reduce is loop that's going through the "timetable" and it is doing two things:

    • add 1 if train comes and subtracts if it departures
    • check what is current number of trains and save max of this value
Thread Thread
 
akhilpokle profile image
Akhil

Wow! This is so efficient! Thanks for sharing it !!