Skip to main content
Back to problems
#1396
Medium Algorithms

Design underground system

Hash Table String Design
74.4% acceptance
Feb 23, 2026
3584
178
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 station stationName at time t. A customer can only be checked into one place at a time. void checkOut(int id, string stationName, int t) A customer with a card ID equal to id, checks out from the station stationName at time t. double getAverageTime(string startStation, string endStation) Returns the average time it takes to travel from startStation to endStation. The average time is computed from all the previous traveling times from startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation. The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation. There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called. 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.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
use std::collections::HashMap;

pub struct UndergroundSystem {
  checkins: HashMap<i32, (String, i32)>,          // id -> (station, time)
  trips: HashMap<(String, String), (f64, i32)>,   // (from, to) -> (total_time, count)
}

impl UndergroundSystem {
  pub fn new() -> Self {
    UndergroundSystem {
      checkins: HashMap::new(),
      trips: HashMap::new(),
    }
  }

  pub fn check_in(&mut self, id: i32, station_name: String, t: i32) {
    self.checkins.insert(id, (station_name, t));
  }

  pub fn check_out(&mut self, id: i32, station_name: String, t: i32) {
    if let Some((start, t0)) = self.checkins.remove(&id) {
      let entry = self.trips.entry((start, station_name)).or_insert((0.0, 0));
      entry.0 += (t - t0) as f64;
      entry.1 += 1;
    }
  }

  pub fn get_average_time(&self, start_station: String, end_station: String) -> f64 {
    let (total, count) = self.trips[&(start_station, end_station)];
    total / count as f64
  }
}