Design Underground System

MediumDesigndesign

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A metro network logs riders tapping in and out, and needs the average travel time between any two stations. Implement: - UndergroundSystem() creates the tracker. - checkIn(id, stationName, t) records that rider id entered at stationName at time t. - checkOut(id, stationName, t) records that rider id left at stationName at time t, completing a trip that started at their matching check-in. - getAverageTime(startStation, endStation) returns the mean duration (checkOut t - checkIn t) over **all completed trips from startStation to endStation**, as a float. Direction matters: trips from A to B and from B to A are averaged separately. Inputs are consistent: a rider is checked in to at most one station at a time, check-out always follows a check-in by the same rider at a strictly later time, and getAverageTime is only called for a pair with at least one completed trip. Answers within 1e-6 are accepted.

Examples

Input: ["UndergroundSystem","checkIn","checkIn","checkOut","checkOut","getAverageTime","checkIn","checkOut","getAverageTime","getAverageTime"] [[],[1,"A",3],[2,"A",5],[1,"B",10],[2,"B",14],["A","B"],[1,"B",20],[1,"A",26],["B","A"],["A","B"]]
Output: [null,null,null,null,null,8.0,null,null,6.0,8.0]
A→B trips take 7 and 9, averaging 8.0. Rider 1 then rides B→A in 6. That is a different route, so A→B stays at 8.0.
Input: ["UndergroundSystem","checkIn","checkOut","checkIn","checkOut","checkIn","checkOut","getAverageTime"] [[],[7,"X",1],[7,"Y",4],[8,"X",5],[8,"Y",6],[9,"X",7],[9,"Y",11],["X","Y"]]
Output: [null,null,null,null,null,null,null,2.6666666666666665]
Durations 3, 1 and 4 average to 8 / 3 ≈ 2.66667.

Constraints

  • 1 <= id, t <= 10^6
  • Station names are 1–10 letters and digits
  • All calls are consistent as described.
  • At most 2 * 10^4 calls in total.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More design problems