1396. Design Underground System
Problem description:
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.
Implement the UndergroundSystem
class:
void checkIn(int id, string stationName, int t)
- A customer with a card ID equal to
id
, checks in at the stationstationName
at timet
. - A customer can only be checked into one place at a time.
- A customer with a card ID equal to
void checkOut(int id, string stationName, int t)
- A customer with a card ID equal to
id
, checks out from the stationstationName
at timet
.
- A customer with a card ID equal to
double getAverageTime(string startStation, string endStation)
- Returns the average time it takes to travel from
startStation
toendStation
. - The average time is computed from all the previous traveling times from
startStation
toendStation
that happened directly, meaning a check in atstartStation
followed by a check out fromendStation
. - The time it takes to travel from
startStation
toendStation
may be different from the time it takes to travel fromendStation
tostartStation
. - There will be at least one customer that has traveled from
startStation
toendStation
beforegetAverageTime
is called.
- Returns the average time it takes to travel from
You may assume all calls to the checkIn
and checkOut
methods are consistent. If a customer checks in at time t1
then checks out at time t2
, then t1 < t2
. All events happen in chronological order.
Example 1:
1 | Input |
Solution:
We have several persons, defined by id
, which Check In at some station
and some time
and then Check Out from some other station at another time. We need to calculate times this person spend to go from one station to another and then calculate average time for all persons. Let us keep 3 pieces of information:
self.ids
is dictionary, where for each person(id) we will keep pair(station, time)
if the last action this person did is check In and empty if it was check OUtself.pairs
is counter, where for each pair of stations we keep total time spend between two stations.self.freqs
is counter, where for each pair of stations we keep how many trips we have between these two stations.
Now, let us discuss, what our functions will do:
checkIn(self, id, stationName, t)
: we just put pair(stationName, t)
intoself.ids[id]
.checkOut(self, id, stationName, t)
. Here we look at personid
, extract information about his last station visited (pop it fromself.ids[id]
and updateself.pairs
,self.freqs
for these pairs of stations.getAverageTime(self, startStation, endStation)
: here we just look at dictionariesself.pairs
andself.freqs
and directly return result.
1 | class UndergroundSystem: |
time complexity: $O(1)$ for all operation
space complexity: $O(Q)$, Q is total number of queries
reference:
related problem: