#1396
Design Underground System
MediumHash TableStringDesignHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) for checkIn and checkOut, O(1) for getAverageTime |
| Space | O(1) | O(n) for storing check-ins and travel times |
💡
Intuition
Time O(1) for checkIn and checkOut, O(1) for getAverageTimeSpace O(n) for storing check-ins and travel times
The optimal solution uses two hash maps: one to store the check-in data and another to store cumulative travel times and counts for each route. This allows us to compute averages in constant time after the initial check-in and check-out operations.
⚙️
Algorithm
5 steps- 1Step 1: Create a hash map to store check-in data with customer ID as the key.
- 2Step 2: Create another hash map to store cumulative travel times and counts for each route (startStation-endStation).
- 3Step 3: For checkIn, store the station and time in the first hash map.
- 4Step 4: For checkOut, calculate the travel time, update the cumulative travel time and count in the second hash map.
- 5Step 5: For getAverageTime, retrieve the total travel time and count for the route and compute the average.
solution.py22 lines
1class UndergroundSystem:
2 def __init__(self):
3 self.checkins = {}
4 self.travel_times = {}
5 self.counts = {}
6
7 def checkIn(self, id: int, stationName: str, t: int) -> None:
8 self.checkins[id] = (stationName, t)
9
10 def checkOut(self, id: int, stationName: str, t: int) -> None:
11 station, checkin_time = self.checkins.pop(id)
12 travel_time = t - checkin_time
13 route = (station, stationName)
14 if route not in self.travel_times:
15 self.travel_times[route] = 0
16 self.counts[route] = 0
17 self.travel_times[route] += travel_time
18 self.counts[route] += 1
19
20 def getAverageTime(self, startStation: str, endStation: str) -> float:
21 route = (startStation, endStation)
22 return self.travel_times[route] / self.counts[route]ℹ
Complexity note: The time complexity is O(1) for both checkIn and checkOut operations because we are using hash maps for constant time access. The getAverageTime operation is also O(1) as it retrieves pre-computed totals and counts.
- 1Using hash maps allows for efficient storage and retrieval of data, which is crucial for performance in this problem.
- 2Maintaining separate counts and total travel times for each route enables quick average calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.