SDE & MLE Prep

1396. Design Underground System

Problem

Design UndergroundSystem: checkIn(id, station, t) and checkOut(id, station, t) record a traveller's trip, and getAverageTime(start, end) returns the average duration of all completed trips that went directly from start to end (at least one exists). A traveller is checked into at most one station at a time.

Example: trips Leyton → Waterloo taking 12 and 10 → getAverageTime("Leyton","Waterloo") = 11.0

checkIn stores id → (station, time); checkOut pops it and accumulates (start, end) → [total time, trips].

Complexity: O(1) per operation.

class UndergroundSystem:
    def __init__(self):
        self.active, self.stats = {}, defaultdict(lambda: [0, 0])

    def checkIn(self, id: int, stationName: str, t: int) -> None:
        self.active[id] = (stationName, t)

    def checkOut(self, id: int, stationName: str, t: int) -> None:
        start, t0 = self.active.pop(id)
        s = self.stats[(start, stationName)]
        s[0] += t - t0
        s[1] += 1

    def getAverageTime(self, startStation: str, endStation: str) -> float:
        total, n = self.stats[(startStation, endStation)]
        return total / n