Design Underground System

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Design a system to track transit times between stations and compute average travel times.

Implement a function that processes an array of operations and an array of arguments:

  • "UndergroundSystem" — Initializes the system.
  • "checkIn" — A customer with customerId checks in at stationName at time t.
  • "checkOut" — A customer with customerId checks out at stationName at time t.
  • "getAverageTime" — Returns the average travel time from startStation to endStation (rounded to 5 decimal places).

Customers are guaranteed to check in before checking out, and each customer checks in only once at a time.

Examples

Example 1:

Input: operations = ["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","checkIn","checkOut","getAverageTime"], args = [[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],[10,"Leyton",24],[10,"Waterloo",38],["Leyton","Waterloo"]]

Output: [null,null,null,null,null,null,null,14.0,null,null,12.0]

Explanation: Paradise→Cambridge: one trip of 14 mins → avg 14.0. Leyton→Waterloo: trips of 12 and 14 mins (avg=13)... wait — trips: 45: 15-3=12, 27: 20-10=10, 10: 38-24=14. Leyton→Waterloo: (12+10+14)/3=12.0.

Example 2:

Input: operations = ["UndergroundSystem","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime"], args = [[],[1,"A",1],[1,"B",5],["A","B"],[2,"A",3],[2,"B",10],["A","B"]]

Output: [null,null,null,4.0,null,null,5.5]

Explanation: First trip A→B: 4 mins. Second trip A→B: 7 mins. Average = (4+7)/2 = 5.5.

Constraints

  • 1 <= id, t <= 10^6
  • 1 <= stationName.length <= 10
  • At most 2 * 10^4 calls to checkIn, checkOut, and getAverageTime
  • All getAverageTime calls use valid startStation/endStation routes that have been traveled
Source: Custom Data Structures pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle