Design Underground System (LeetCode 1396): Solution and Explanation

Medium
Hash Table
String
Design

Riders check in at a station, later check out at another, and you must report the average travel time between any two stations over all completed trips. Implement checkIn, checkOut and getAverageTime.

Intuition

A trip has two halves that arrive at different times. At checkIn you only know where and when the rider entered. The route is not known until checkOut, so the first thing to store is the open check-in, keyed by card id, since a rider can only be checked in once at a time.

When the rider checks out, pull that record back out. The start station, the exit station and the two times give one complete trip on the route (start, end), with duration t - t0. The record is no longer needed, so remove it.

Now ask what getAverageTime really needs. It never looks at individual trips, only their mean, and a mean is just a sum divided by a count. So keep, for every route, the running total of durations and the number of trips. Adding a trip is two additions, and the average is one division.

The route is directional, because travel times can differ by direction, so the key must be the ordered pair (start, end), not an unordered set of two stations.

Approach: Open check-ins plus route totals

  1. Keep check_ins, a map from card id to (station, time), and totals, a map from (start, end) to (total, count).
  2. checkIn(id, station, t): store check_ins[id] = (station, t).
  3. checkOut(id, station, t): pop (start, t0) from check_ins[id], then add t - t0 to the total and 1 to the count of totals[(start, station)].
  4. getAverageTime(start, end): look up (total, count) for (start, end) and return total / count as a float.

Step-by-step example

Example 1: riders 45, 32, 27 check in; 45, 27, 32 check out; two averages; rider 10 rides; two more averages
  1. checkIn(45, Leyton, 3), checkIn(32, Paradise, 8), checkIn(27, Leyton, 10): three open records.
  2. checkOut(45, Waterloo, 15): trip Leyton to Waterloo took 12, so totals[(Leyton, Waterloo)] = (12, 1).
  3. checkOut(27, Waterloo, 20): another 10 on the same route, so (22, 2). checkOut(32, Cambridge, 22): totals[(Paradise, Cambridge)] = (14, 1).
  4. getAverageTime(Paradise, Cambridge) = 14 / 1 = 14.0. getAverageTime(Leyton, Waterloo) = 22 / 2 = 11.0.
  5. checkIn(10, Leyton, 24) and the average is still 11.0, because an open trip does not count yet.
  6. checkOut(10, Waterloo, 38) adds 14, giving (36, 3), so the last average is 12.0.

Code: Python, Java, C++

1class UndergroundSystem:
2    def __init__(self):
3        self.check_ins = {}
4        self.totals = {}
5
6    def checkIn(self, id: int, stationName: str, t: int) -> None:
7        self.check_ins[id] = (stationName, t)
8
9    def checkOut(self, id: int, stationName: str, t: int) -> None:
10        start, t0 = self.check_ins.pop(id)
11        key = (start, stationName)
12        total, count = self.totals.get(key, (0, 0))
13        self.totals[key] = (total + t - t0, count + 1)
14
15    def getAverageTime(self, startStation: str, endStation: str) -> float:
16        total, count = self.totals[(startStation, endStation)]
17        return total / count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(1) per call

Each call does a constant number of hash map lookups and updates. Hashing a station name costs time proportional to its length, which is at most 10.

Space

O(P + R)

P is the number of riders currently checked in and R is the number of distinct routes that have seen a completed trip.

Other approaches

Store every trip (time O(1) check-in and check-out, O(k) average, space O(total trips))

Append each trip duration to a list per route and average the list on request. It works, but getAverageTime becomes O(trips on that route) and memory grows with every trip.

String keys instead of tuples (time O(1) per call, space O(P + R))

In languages without hashable tuples, join the two station names with a separator that cannot appear in a name, such as "->". The logic is identical.

Common mistakes

  • Treating (A, B) and (B, A) as the same route. The problem asks for the directional average.
  • Using integer division for the average. Return a floating-point result, for example total / count in Python 3 or a cast to double in Java and C++.
  • Keeping the check-in record after check-out. The same card can check in again later, so stale records waste memory and can confuse debugging.
  • Concatenating station names without a separator. "AB" + "C" and "A" + "BC" would collide.

Frequently asked questions

Why store a sum and a count instead of the average itself?

Updating an average needs the count anyway, and recomputing it from a rounded average loses precision. A running sum and count give an exact average on every query.

Can total time overflow?

At most 10^4 trips can each last up to 10^6, so the total stays under 10^10. That exceeds a 32-bit int, so use a 64-bit integer or a double for the total in typed languages.

Do riders who are still inside affect the average?

No. Only completed trips are added to the route totals, so an open check-in has no effect until its check-out.