Skip to content

Instantly share code, notes, and snippets.

@cfrank
Created May 31, 2023 23:51
Show Gist options
  • Save cfrank/3631b985d3c1dd611554167c969d643e to your computer and use it in GitHub Desktop.
Save cfrank/3631b985d3c1dd611554167c969d643e to your computer and use it in GitHub Desktop.
1396. Design Underground System
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