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.
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.
Examples
Example 1:
Input
|
|
Output
|
|
Explanation
|
|
Example 2:
Input
|
|
Output
|
|
Explanation
|
|
Solution
Method 1 – HashMap for Check-In and Trip Data
Intuition
To efficiently track customer journeys and compute average travel times, we use a hash map to record check-in information for each customer and another hash map to aggregate total travel times and trip counts for each station pair. This allows quick updates and queries for average times.
Approach
- Use a hash map to store each customer’s check-in station and time.
- Use another hash map to store the total time and count of trips for each (start station, end station) pair.
- On check-in, record the customer’s station and time.
- On check-out, calculate the trip duration, update the total time and count for the station pair, and remove the customer’s check-in record.
- On averageTime query, return the total time divided by the count for the requested station pair.
Complexity
- ⏰ Time complexity:
O(1)
for all operations, as all updates and queries are direct hash map accesses. - 🧺 Space complexity:
O(n)
, where n is the number of customers and station pairs tracked.
C++
|
|
Java
|
|
Python
|
|