Design Underground System (LeetCode 1396): Solution and Explanation
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
- Keep
check_ins, a map from card id to(station, time), andtotals, a map from(start, end)to(total, count). checkIn(id, station, t): storecheck_ins[id] = (station, t).checkOut(id, station, t): pop(start, t0)fromcheck_ins[id], then addt - t0to the total and 1 to the count oftotals[(start, station)].getAverageTime(start, end): look up(total, count)for(start, end)and returntotal / countas 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
- checkIn(45, Leyton, 3), checkIn(32, Paradise, 8), checkIn(27, Leyton, 10): three open records.
- checkOut(45, Waterloo, 15): trip Leyton to Waterloo took 12, so totals[(Leyton, Waterloo)] = (12, 1).
- checkOut(27, Waterloo, 20): another 10 on the same route, so (22, 2). checkOut(32, Cambridge, 22): totals[(Paradise, Cambridge)] = (14, 1).
- getAverageTime(Paradise, Cambridge) = 14 / 1 = 14.0. getAverageTime(Leyton, Waterloo) = 22 / 2 = 11.0.
- checkIn(10, Leyton, 24) and the average is still 11.0, because an open trip does not count yet.
- 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 / count1class UndergroundSystem {
2 private Map<Integer, String> inStation;
3 private Map<Integer, Integer> inTime;
4 private Map<String, long[]> totals;
5
6 public UndergroundSystem() {
7 inStation = new HashMap<>();
8 inTime = new HashMap<>();
9 totals = new HashMap<>();
10 }
11
12 public void checkIn(int id, String stationName, int t) {
13 inStation.put(id, stationName);
14 inTime.put(id, t);
15 }
16
17 public void checkOut(int id, String stationName, int t) {
18 String key = inStation.remove(id) + "->" + stationName;
19 int duration = t - inTime.remove(id);
20 long[] stat = totals.computeIfAbsent(key, k -> new long[2]);
21 stat[0] += duration;
22 stat[1] += 1;
23 }
24
25 public double getAverageTime(String startStation, String endStation) {
26 long[] stat = totals.get(startStation + "->" + endStation);
27 return (double) stat[0] / stat[1];
28 }
29}1class UndergroundSystem {
2 unordered_map<int, pair<string, int>> checkIns;
3 unordered_map<string, pair<long long, int>> totals;
4
5public:
6 UndergroundSystem() {}
7
8 void checkIn(int id, string stationName, int t) {
9 checkIns[id] = {stationName, t};
10 }
11
12 void checkOut(int id, string stationName, int t) {
13 pair<string, int> entry = checkIns[id];
14 checkIns.erase(id);
15 string key = entry.first + "->" + stationName;
16 totals[key].first += t - entry.second;
17 totals[key].second += 1;
18 }
19
20 double getAverageTime(string startStation, string endStation) {
21 pair<long long, int>& stat = totals[startStation + "->" + endStation];
22 return (double) stat.first / stat.second;
23 }
24};Time and space complexity
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.
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 / countin 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.