Open trips + route totals
Time O(1) per call Space O(customers + routes)open: id → {station, time}. routes: "A->B" → {total time, count}. checkOut closes the trip and updates totals; the average is total / count.
checkIn(10, Leyton, 3), checkOut(10, Paradise, 8), getAverageTime(Leyton, Paradise)open(map)
routes {total, trips}(map)
empty
Step 1/3checkIn: remember where and when customer 10 started.
import java.util.*;
class UndergroundSystem {
private record Trip(String station, int time) {}
private final Map<Integer, Trip> open = new HashMap<>();
private final Map<String, long[]> routes = new HashMap<>(); // {total time, trips}
public UndergroundSystem() {}
public void checkIn(int id, String stationName, int t) { open.put(id, new Trip(stationName, t)); }
public void checkOut(int id, String stationName, int t) {
Trip trip = open.remove(id);
long[] r = routes.computeIfAbsent(trip.station() + "->" + stationName, k -> new long[2]);
r[0] += t - trip.time();
r[1]++;
}
public double getAverageTime(String startStation, String endStation) {
long[] r = routes.get(startStation + "->" + endStation);
return (double) r[0] / r[1];
}
}Verdict: Never stores the full trip history.