Created
May 31, 2023 23:51
-
-
Save cfrank/3631b985d3c1dd611554167c969d643e to your computer and use it in GitHub Desktop.
1396. Design Underground System
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UndergroundSystem { | |
#stationTripLengthMap; | |
#inFlightTrips; | |
constructor() { | |
this.#stationTripLengthMap = {}; | |
this.#inFlightTrips = {}; | |
} | |
checkIn(id, stationName, t) { | |
this.#inFlightTrips[id] = [stationName, t]; | |
} | |
checkOut(id, stationName, t) { | |
const [startingStation, startTime] = this.#inFlightTrips[id]; | |
const tripTime = t - startTime; | |
delete this.#inFlightTrips[id]; | |
const stationTripLength = this.#stationTripLengthMap?.[startingStation]; | |
if (!stationTripLength) { | |
this.#stationTripLengthMap[startingStation] = { | |
[stationName]: [tripTime], | |
}; | |
return; | |
} | |
if (Array.isArray(stationTripLength?.[stationName])) { | |
stationTripLength[stationName].push(tripTime); | |
} else { | |
stationTripLength[stationName] = [tripTime]; | |
} | |
} | |
getAverageTime(startStation, endStation) { | |
const tripTimes = this.#stationTripLengthMap[startStation]?.[endStation]; | |
const totalTripTime = tripTimes.reduce((total, tripTime) => { | |
return total + tripTime; | |
}, 0); | |
return totalTripTime / tripTimes.length; | |
} | |
} | |
/** | |
* Your UndergroundSystem object will be instantiated and called as such: | |
* var obj = new UndergroundSystem() | |
* obj.checkIn(id,stationName,t) | |
* obj.checkOut(id,stationName,t) | |
* var param_3 = obj.getAverageTime(startStation,endStation) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment