DEV Community

codingpineapple
codingpineapple

Posted on

LeetCode 1396. Design Underground System (javascript solution)

Description:

An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.

Implement the UndergroundSystem class:

void checkIn(int id, string stationName, int t)
A customer with a card ID equal to id, checks in at the station stationName at time t.
A customer can only be checked into one place at a time.
void checkOut(int id, string stationName, int t)
A customer with a card ID equal to id, checks out from the station stationName at time t.
double getAverageTime(string startStation, string endStation)
Returns the average time it takes to travel from startStation to endStation.
The average time is computed from all the previous traveling times from startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation.
The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation.
There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called.
You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in chronological order.

class UndergroundSystem {
    // class constructor
    constructor() {
        // check ins are of type {id : {checkIn time, station name}}
        this.checkIns = {};
        // trips are of type {route : [full elapsed times]}
        this.trips = {};
    }

    checkIn(id, stationName, t) {
        // log check in
        this.checkIns[id] = {
            t: t,
            stationName: stationName,
        };
    }

    checkOut(id, stationName, t) {
        // create route string
        const route = this.checkIns[id].stationName +
            '=>' +
            stationName;
        // check if this route is not in trips obj yet
        if (!(route in this.trips))
            this.trips[route] = [];
        // push elapsed time to route: trips
        this.trips[route].push(t - this.checkIns[id].t);
    }

    getAverageTime(startStation, endStation) {
        // create route string
        const route = startStation + '=>' + endStation;
        // running sum
        let sum = 0;
        // iterate thru all elapsed trip times for this route
        for (let i = 0; i < this.trips[route].length; i++) {
            // add to running sum
            sum += this.trips[route][i];
        }
        // return avg
        return sum / this.trips[route].length;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)