Problem
Track customers checking in and out of an underground system, and return the average travel time between two stations. A customer can be in at most one journey at a time, and they always check out after checking in.
Original: LeetCode 1396: Design Underground System.
Examples
Example 1
`UndergroundSystem: checkIn(45, "Leyton", 3), checkIn(32, "Paradise", 8), checkIn(27, "Leyton", 10), checkOut(45, "Waterloo", 15), checkOut(27, "Waterloo", 20), checkOut(32, "Cambridge", 22), getAverageTime("Paradise", "Cambridge"), getAverageTime("Leyton", "Waterloo"), checkIn(10, "Leyton", 24), getAverageTime("Leyton", "Waterloo"), checkOut(10, "Waterloo", 38), getAverageTime("Leyton", "Waterloo")``[null, null, null, null, null, null, 14.0, 11.0, null, 11.0, null, 12.0]`Constraints
1 <= id, t <= 10^61 <= stationName.length, startStation.length, endStation.length <= 10- All strings consist of uppercase and lowercase English letters and digits.
- There will be at most
2 * 10^4calls in total tocheckIn,checkOut, andgetAverageTime. - Answers within
10^-5of the actual value will be accepted.
Hints
Hint 1
Averages are over all completed trips between a start and an end station, not per customer. Later trips should change the average.
Hint 2
This is event tracking: an open-trip map plus an aggregate map of (start, end) to (total time, trip count).
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Store every completed trip and average them on each query. That is correct but uses more memory than a running sum.
Optimal. HashMap from id to (station, time), and HashMap from a station-pair key to a running sum and count.
Alternative. You can keep a list of times per pair if you later need percentiles as well as the mean.
Complexity
- Time
- O(1)
Each method is O(1) average time. Space is O(open journeys + station pairs).
- Space
- O(open journeys + station pairs)
Code
class UndergroundSystem:
def __init__(self) -> None:
self.open: dict[int, tuple[str, int]] = {}
self.stats: dict[tuple[str, str], list[int]] = {}
def check_in(self, id: int, station_name: str, t: int) -> None:
self.open[id] = (station_name, t)
def check_out(self, id: int, station_name: str, t: int) -> None:
start, t0 = self.open.pop(id)
key = (start, station_name)
total, count = self.stats.get(key, [0, 0])
self.stats[key] = [total + (t - t0), count + 1]
def get_average_time(self, start_station: str, end_station: str) -> float:
total, count = self.stats[(start_station, end_station)]
return total / count
if __name__ == "__main__":
u = UndergroundSystem()
u.check_in(45, "Leyton", 3)
u.check_in(32, "Paradise", 8)
u.check_in(27, "Leyton", 10)
u.check_out(45, "Waterloo", 15)
u.check_out(27, "Waterloo", 20)
u.check_out(32, "Cambridge", 22)
assert u.get_average_time("Paradise", "Cambridge") == 14.0
assert u.get_average_time("Leyton", "Waterloo") == 11.0
u.check_in(10, "Leyton", 24)
assert u.get_average_time("Leyton", "Waterloo") == 11.0
u.check_out(10, "Waterloo", 38)
assert u.get_average_time("Leyton", "Waterloo") == 12.0
print("ok")import java.util.HashMap;
import java.util.Map;
public class DesignUndergroundSystem {
private final Map<Integer, CheckIn> open = new HashMap<>();
private final Map<String, long[]> stats = new HashMap<>();
void checkIn(int id, String stationName, int t) {
open.put(id, new CheckIn(stationName, t));
}
void checkOut(int id, String stationName, int t) {
var in = open.remove(id);
String key = in.station + "->" + stationName;
var s = stats.computeIfAbsent(key, k -> new long[2]);
s[0] += t - in.time;
s[1]++;
}
double getAverageTime(String startStation, String endStation) {
var s = stats.get(startStation + "->" + endStation);
return (double) s[0] / s[1];
}
static class CheckIn {
String station;
int time;
CheckIn(String station, int time) { this.station = station; this.time = time; }
}
public static void main(String[] args) {
var u = new DesignUndergroundSystem();
u.checkIn(45, "Leyton", 3);
u.checkIn(32, "Paradise", 8);
u.checkIn(27, "Leyton", 10);
u.checkOut(45, "Waterloo", 15);
u.checkOut(27, "Waterloo", 20);
u.checkOut(32, "Cambridge", 22);
if (u.getAverageTime("Paradise", "Cambridge") != 14.0) throw new AssertionError();
if (u.getAverageTime("Leyton", "Waterloo") != 11.0) throw new AssertionError();
u.checkIn(10, "Leyton", 24);
if (u.getAverageTime("Leyton", "Waterloo") != 11.0) throw new AssertionError();
u.checkOut(10, "Waterloo", 38);
if (u.getAverageTime("Leyton", "Waterloo") != 12.0) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official sample: trips 45 Leyton to Waterloo in 12, 27 Leyton to Waterloo in 10, and 32 Paradise to Cambridge in 14. The Leyton-Waterloo average is 11, then a later 14-minute trip raises it to 12. Paradise-Cambridge is 14.
- Averages are not reset by later check-ins that have not yet checked out.
Follow-ups
- If you also needed p95 latency, you would store the raw times or a histogram, not only the sum and the count.
Interview script
"I keep the open check-in by customer id, and a running sum and count for each start-end pair. The average is just the sum divided by the number of completed trips."
Source: LeetCode 1396: Design Underground System
Sources
- LeetCode 1603: Design Parking System
- LeetCode 705: Design HashSet
- Java SE 17 API: ArrayList.remove)
- LeetCode 380: Insert Delete GetRandom O(1)
- Java SE 17 API: Random.nextInt)
- LeetCode 146: LRU Cache
- Java SE 17 API: HashMap
- LeetCode 460: LFU Cache
- Java SE 17 API: LinkedHashSet
- LeetCode 981: Time Based Key-Value Store
- LeetCode 208: Implement Trie (Prefix Tree)
- LeetCode 211: Design Add and Search Words Data Structure
- LeetCode 355: Design Twitter
- Java SE 17 API: PriorityQueue
- LeetCode 1396: Design Underground System
Sources (1)
- LeetCode 1396: Design Underground Systemleetcode.com