Design Underground System — LeetCode 1396 Python Solution
- Problem
- #1396
- Pattern
- Hash Map
- Reading time
- 5 min
- Source
- leetcode.com
The problem
An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.
Example
- Input
- ["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"]
- Output
- [null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]
- Explanation
- UndergroundSystem undergroundSystem = new UndergroundSystem();
Python solution
class UndergroundSystem:
def __init__(self):
self.ts = {}
self.d = {}
def checkIn(self, id: int, stationName: str, t: int) -> None:
self.ts[id] = (t, stationName)
def checkOut(self, id: int, stationName: str, t: int) -> None:
t0, station = self.ts[id]
x = self.d.get((station, stationName), (0, 0))
self.d[(station, stationName)] = (x[0] + t - t0, x[1] + 1)
def getAverageTime(self, startStation: str, endStation: str) -> float:
x = self.d[(startStation, endStation)]
return x[0] / x[1]
# Your UndergroundSystem object will be instantiated and called as such:
# obj = UndergroundSystem()
# obj.checkIn(id,stationName,t)
# obj.checkOut(id,stationName,t)
# param_3 = obj.getAverageTime(startStation,endStation)Complexity
| Measure | Complexity |
|---|---|
| Time | O(1) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1396. Design Underground System is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1396. Design Underground System?
- LeetCode 1396. Design Underground System is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1396. Design Underground System?
- The Python solution on this page runs in O(1).
- What is the space complexity of LeetCode 1396. Design Underground System?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1396. Design Underground System cover?
- LeetCode 1396. Design Underground System is tagged Design, Hash Table and String on LeetCode.