Design Underground System solution explained

Design Underground System asks you to record when riders tap in and out of stations and to report the average travel time between any two stations. Two hash maps solve it: one from rider id to the open check-in (station and time), and one from the ordered station pair to a running total of minutes and a trip count. Every call is O(1), and the average is just total divided by count.

By Published 7 min read

The task, restated

A transit network logs taps. check_in(id, station, t) says rider id entered at station at time t. check_out(id, station, t) says the same rider left at station at time t, which completes one trip. average_time(start, end) returns the mean duration of every completed trip that began at start and ended at end. You may assume calls are consistent: a rider is checked in at most once at a time, check-out always follows check-in, times increase, and an average is only requested for a pair with at least one finished trip.

A made-up day on a two-station line
CallEffect or result
check_in(7, Elm, 3)rider 7 is open at Elm since minute 3
check_in(8, Elm, 5)rider 8 is open at Elm since minute 5
check_out(7, Pier, 15)trip Elm to Pier, 12 minutes
check_in(9, Pier, 16)rider 9 is open at Pier
check_out(8, Pier, 23)trip Elm to Pier, 18 minutes
average_time(Elm, Pier)(12 + 18) / 2 = 15.0
check_out(9, Elm, 30)trip Pier to Elm, 14 minutes
average_time(Pier, Elm)14.0; the reverse direction is tracked separately
check_in(7, Elm, 40), check_out(7, Pier, 49)rider 7 again, 9 minutes
average_time(Elm, Pier)(12 + 18 + 9) / 3 = 13.0
A made-up day on a two-station line. Scroll sideways on a small screen.

Two clarifying questions shape the answer. Should A to B and B to A be averaged together? Normally not, since uphill and downhill trips differ. And what precision is expected for the average? Returning a float is standard; keeping the running total as an integer avoids rounding drift until the final division.

Why it gets asked

It is a realistic data-modeling question disguised as a coding problem. There is no tricky algorithm; the score depends on choosing keys well, keeping only what the queries need, and thinking about what happens at scale. Follow-up questions tend to push in these directions:

  • Report the median or the 90th percentile instead of the mean. Running sums are no longer enough; you need the trip times themselves, kept sorted or in two heaps per pair.
  • Average only the last N trips. Keep a fixed-size queue of durations per pair and adjust the sum as old trips fall off.
  • Riders who never check out. Their open entries pile up; expire them after a time limit.
  • Many machines writing at once. The totals per pair can be sharded by pair; each update is a commutative add, which makes merging simple.

A slow start: store every trip

A natural first version records each finished trip as (start, end, minutes) in one list, then scans the list to average a pair. Check-in and check-out are O(1), but each average costs O(number of trips), and memory grows forever. Say it, then point out that the query only ever needs a sum and a count per pair, which is the step to the real answer.

class TripLog:
    def __init__(self):
        self.open = {}
        self.trips = []

    def check_in(self, rider, station, t):
        self.open[rider] = (station, t)

    def check_out(self, rider, station, t):
        start, t0 = self.open.pop(rider)
        self.trips.append((start, station, t - t0))

    def average_time(self, start, end):
        times = [m for a, b, m in self.trips if a == start and b == end]
        return sum(times) / len(times)
Python: every trip kept, every average a full scan.

Optimal approach: open trips plus running totals

Keep two maps. open maps a rider id to the station and time of the check-in that has not been closed yet. totals maps an ordered pair (start, end) to [sum of minutes, number of trips]. Check-in writes to open. Check-out removes the rider from open, computes the duration, and adds it to the pair's totals. The average is the sum divided by the count. Removing the rider on check-out matters: it keeps open small, and it lets the same rider ride again later without confusion.

class UndergroundSystem:
    def __init__(self):
        self.open = {}  # rider -> (station, time)
        self.totals = {}  # (start, end) -> [minutes, trips]

    def check_in(self, rider, station, t):
        self.open[rider] = (station, t)

    def check_out(self, rider, station, t):
        start, t0 = self.open.pop(rider)
        pair = self.totals.setdefault((start, station), [0, 0])
        pair[0] += t - t0
        pair[1] += 1

    def average_time(self, start, end):
        minutes, trips = self.totals[(start, end)]
        return minutes / trips
Python: tuple keys for the station pair.
class UndergroundSystem {
  constructor() {
    this.open = new Map();
    this.totals = new Map();
  }

  checkIn(rider, station, t) {
    this.open.set(rider, [station, t]);
  }

  checkOut(rider, station, t) {
    const [start, t0] = this.open.get(rider);
    this.open.delete(rider);
    if (!this.totals.has(start)) this.totals.set(start, new Map());
    const byEnd = this.totals.get(start);
    const pair = byEnd.get(station) || [0, 0];
    pair[0] += t - t0;
    pair[1] += 1;
    byEnd.set(station, pair);
  }

  averageTime(start, end) {
    const [minutes, trips] = this.totals.get(start).get(end);
    return minutes / trips;
  }
}
JavaScript: a nested Map avoids building string keys.

Why a nested Map in JavaScript? A Map cannot use an array as a key by value, so the usual shortcut is to glue the names into one string with a separator. That works until a station name contains the separator, at which point two different pairs can collide. The nested Map sidesteps the question. In Python, tuples hash by value, so (start, end) is a safe key as is.

Time and space

R riders currently checked in, P station pairs seen, T finished trips
Designcheck_incheck_outaverage_timeSpace
Store every tripO(1)O(1)O(T)O(R + T)
Running totals per pairO(1)O(1)O(1)O(R + P)
Sorted durations per pair (median follow-up)O(1)O(log T) with two heapsO(1) for the medianO(R + T)
R riders currently checked in, P station pairs seen, T finished trips. Scroll sideways on a small screen.

The running-totals design uses memory proportional to the number of distinct pairs, which is bounded by the square of the station count no matter how many trips happen. That bound is a nice point to make when the interviewer asks about a network running for years.

Edge cases

  • A rider checks out at the same station they entered. Treat (A, A) as an ordinary pair unless told otherwise.
  • The same rider takes several trips: popping the open entry on check-out keeps each trip separate.
  • Several riders open at once with the same start station: each has its own entry keyed by id.
  • Trips with duration 0 are valid if check-in and check-out share a timestamp.
  • Very large sums: Python integers do not overflow; in other languages, use a 64-bit total.

Mistakes to avoid

  • Keying totals by the unordered pair, merging both directions.
  • Keying open trips by station instead of by rider, which breaks when two riders enter the same station.
  • Leaving the rider in open after check-out, so a later bug or a re-entry reads stale data.
  • Storing averages and updating them incrementally with floats, which accumulates rounding error. Store the sum and the count.
  • Building JavaScript keys like start plus end with no separator, so stations AB plus C collide with A plus BC.

How to explain it out loud

Fictional example

Starting from what the query needs
Candidate
The only query is an average per ordered station pair, so for each pair I just need a total and a count. I don't need to keep individual trips.
Candidate
One map holds open check-ins by rider: station and time. On check-out I pop that entry, compute the duration, and add it to the totals for start and end in that order.
Candidate
Every call is constant time, and memory is riders in transit plus station pairs. If you later want a median, I'd need the durations themselves, so I'd switch to two heaps per pair.

Design Browser History is another short class design where the right fields make every method trivial. Snapshot Array also records values over time, but has to answer questions about the past, which brings in binary search. Design HashMap explains what the two maps here are doing underneath.

Practicing with Natively

On a Mac or Windows PC, Natively can capture a design prompt from your screen in practice and suggest a class layout and code for you to compare. More useful for this kind of question, it transcribes your answer, so you can reread whether you explained why the pair is ordered and why you store sums rather than averages. The AI interview assistant page has the details.

Questions people ask

How do you solve Design Underground System?

Use two hash maps. One maps a rider id to the station and time of their open check-in. The other maps the ordered pair (start, end) to a running sum of minutes and a trip count. The average is the sum divided by the count.

What is the time complexity of Design Underground System?

check_in, check_out and average_time are all O(1). Space is O(R + P), where R is the riders currently checked in and P is the station pairs seen, instead of growing with every finished trip.

Should trips from A to B and B to A be averaged together?

Normally not. The totals are keyed by the ordered pair, so A to B and B to A are separate keys. Keying by the unordered pair is a common mistake.

How would you report a median trip time instead of the mean?

Running sums are no longer enough, because a median needs the trip times themselves. Keep the durations per pair, for example in two heaps, which makes check-out O(log T) and the median O(1).

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP