1. Complete Trip Log Scan
Intuition
Keep track of active check-ins in a map. On check-out, record a Trip(startStation, endStation, duration) into a global list. To compute the average, filter all trips matching startStation and endStation, sum their durations, and divide by matching count.
When to apply: When getAverageTime is called rarely and historical trip storage is required.
Algorithm
- Step 1: In checkIn(id, station, t), store map[id] = {station, t}.
- Step 2: In checkOut(id, station, t), retrieve start details, calculate duration = t - startT, push Trip(start, end, duration) into trips array, and erase id from map.
- Step 3: In getAverageTime(start, end), scan trips array, summing durations and counting matches.
- Step 4: Return sum / count.
#include <iostream>#include <string>#include <vector>#include <unordered_map> using namespace std; struct Trip { string start, end; int duration;}; class UndergroundSystem { unordered_map<int, pair<string, int>> checkIns; vector<Trip> allTrips;public: UndergroundSystem() {} void checkIn(int id, string stationName, int t) { checkIns[id] = {stationName, t}; } void checkOut(int id, string stationName, int t) { auto [startStation, startTime] = checkIns[id]; checkIns.erase(id); allTrips.push_back({startStation, stationName, t - startTime}); } double getAverageTime(string startStation, string endStation) { double total = 0; int count = 0; for (const auto& trip : allTrips) { if (trip.start == startStation && trip.end == endStation) { total += trip.duration; count++; } } return count == 0 ? 0.0 : total / count; }}; int main() { UndergroundSystem sys; sys.checkIn(45, "Leyton", 3); sys.checkIn(32, "Paradise", 8); sys.checkOut(45, "Waterloo", 15); sys.checkOut(32, "Cambridge", 22); cout << "Avg Paradise->Cambridge: " << sys.getAverageTime("Paradise", "Cambridge") << endl; // 14 cout << "Avg Leyton->Waterloo: " << sys.getAverageTime("Leyton", "Waterloo") << endl; // 12 return 0;}Time & Space Complexity
- Time complexity:
O(1) checkIn/checkOut, O(Total Trips) getAverageTime - Space complexity:
O(Total Trips)