Design Underground System solution and explanation
9 more videos on this problem
Design Underground System - Leetcode 1396 - PythonNeetCodeIO · 8:56 · 11K views
Design Underground System | Full Thought Process | Bloomberg | Amazon | Leetcode 1396codestorywithMIK · 20:26 · 3K views
Design Underground System | Live Coding with Explanation | Leetcode - 1396Algorithms Made Easy · 13:26 · 3K views
Design Underground System | Leetcode 1396 | Hashmap | Day-24Ayushi Sharma · 14:36 · 3K views
Design Underground System || Hash Maps || Design Question || Leetcode 1396Aryan Mittal · 13:28 · 2K views
Leetcode - Design Underground System (Python)Timothy H Chang · 4:53 · 2K views
Leetcode 1396. Design Underground SystemFraz · 5:47 · 1K views
Design Underground System | Leetcode 1396Coding Decoded · 25:50 · 1K views
Leetcode 1396 Design Underground System (Java)TheAnalyticGuy · 17:39 · 479 views
Design Underground System | Leetcode1396 | Class Design 🔥🔥 | Live coding sessionCoding Decoded · 2:10 · 435 views
The problem
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 stationstationNameat timet. - A customer can only be checked into one place at a time.
- A customer with a card ID equal to
void checkOut(int id, string stationName, int t)- A customer with a card ID equal to
id, checks out from the stationstationNameat timet.
- A customer with a card ID equal to
double getAverageTime(string startStation, string endStation)- Returns the average time it takes to travel from
startStationtoendStation. - The average time is computed from all the previous traveling times from
startStationtoendStationthat happened directly, meaning a check in atstartStationfollowed by a check out fromendStation. - The time it takes to travel from
startStationtoendStationmay be different from the time it takes to travel fromendStationtostartStation. - There will be at least one customer that has traveled from
startStationtoendStationbeforegetAverageTimeis called.
- Returns the average time it takes to travel from
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.
Example 1:
Input
["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"]
[[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],["Leyton","Waterloo"],[10,"Leyton",24],["Leyton","Waterloo"],[10,"Waterloo",38],["Leyton","Waterloo"]]
Output
[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]
Explanation
UndergroundSystem undergroundSystem = new UndergroundSystem();
undergroundSystem.checkIn(45, "Leyton", 3);
undergroundSystem.checkIn(32, "Paradise", 8);
undergroundSystem.checkIn(27, "Leyton", 10);
undergroundSystem.checkOut(45, "Waterloo", 15); // Customer 45 "Leyton" -> "Waterloo" in 15-3 = 12
undergroundSystem.checkOut(27, "Waterloo", 20); // Customer 27 "Leyton" -> "Waterloo" in 20-10 = 10
undergroundSystem.checkOut(32, "Cambridge", 22); // Customer 32 "Paradise" -> "Cambridge" in 22-8 = 14
undergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. One trip "Paradise" -> "Cambridge", (14) / 1 = 14
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000. Two trips "Leyton" -> "Waterloo", (10 + 12) / 2 = 11
undergroundSystem.checkIn(10, "Leyton", 24);
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000
undergroundSystem.checkOut(10, "Waterloo", 38); // Customer 10 "Leyton" -> "Waterloo" in 38-24 = 14
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 12.00000. Three trips "Leyton" -> "Waterloo", (10 + 12 + 14) / 3 = 12
Example 2:
Input
["UndergroundSystem","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime"]
[[],[10,"Leyton",3],[10,"Paradise",8],["Leyton","Paradise"],[5,"Leyton",10],[5,"Paradise",16],["Leyton","Paradise"],[2,"Leyton",21],[2,"Paradise",30],["Leyton","Paradise"]]
Output
[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]
Explanation
UndergroundSystem undergroundSystem = new UndergroundSystem();
undergroundSystem.checkIn(10, "Leyton", 3);
undergroundSystem.checkOut(10, "Paradise", 8); // Customer 10 "Leyton" -> "Paradise" in 8-3 = 5
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000, (5) / 1 = 5
undergroundSystem.checkIn(5, "Leyton", 10);
undergroundSystem.checkOut(5, "Paradise", 16); // Customer 5 "Leyton" -> "Paradise" in 16-10 = 6
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000, (5 + 6) / 2 = 5.5
undergroundSystem.checkIn(2, "Leyton", 21);
undergroundSystem.checkOut(2, "Paradise", 30); // Customer 2 "Leyton" -> "Paradise" in 30-21 = 9
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667
Constraints:
1 <= id, t <= 1061 <= stationName.length, startStation.length, endStation.length <= 10- All strings consist of uppercase and lowercase English letters and digits.
- There will be at most
2 * 104calls in total tocheckIn,checkOut, andgetAverageTime. - Answers within
10-5of the actual value will be accepted.
Approach overview
Problem Overview: You need to design a transit tracking system that records when passengers check in and check out of stations. The system must return the average travel time between two stations using historical trip data.
Approach 1: Two Dictionary Method (O(1) per operation, O(n) space)
This approach keeps two hash maps. The first map tracks active trips using id → (stationName, time). When a passenger checks in, store their starting station and timestamp. The second map aggregates completed trips using (startStation, endStation) → (totalTime, tripCount). During checkout, look up the passenger’s start data, compute the trip duration, and update the aggregated totals. The average travel time is simply totalTime / tripCount, retrieved in constant time using a hash lookup.
The key insight is separating active journeys from historical statistics. Active trips require quick lookups by passenger ID, while averages require aggregation by station pair. Using hash tables for both tasks keeps every operation—check-in, check-out, and average query—at constant time. This method is clean, scalable, and mirrors how production analytics pipelines maintain running aggregates.
Approach 2: List Method with String Keys (O(1) per operation, O(n) space)
This variation stores aggregated trip statistics using a single key built from the station names, typically something like "start#end". The active trips are still tracked with an id → (station, time) map, but the historical data uses a string key instead of a tuple or structured pair.
When a passenger checks out, compute the trip duration and update the aggregated record stored under the combined key. A small list or array holds the cumulative travel time and trip count. Queries for the average travel time simply retrieve the aggregated values and compute the ratio.
This design works well in languages where composite keys are inconvenient or where string concatenation is simpler than creating pair objects. The tradeoff is slightly less structured data management, but the algorithmic behavior remains identical: constant-time updates and lookups using hash maps and simple string keys.
Recommended for interviews: The Two Dictionary Method is the expected solution. It demonstrates strong understanding of system design patterns, incremental aggregation, and hash-based lookups. Mentioning the separation between active sessions and aggregated metrics signals clear reasoning. The string-key variant is still valid but mainly reflects language-specific implementation convenience rather than a conceptual improvement.
Approach 1: Two Dictionary Method
In this approach, we use two dictionaries to store the data: one for storing check-in information and another to store route information.
- The check-in dictionary maps a customer's ID to their check-in station and time.
- The route dictionary maps a tuple of (startStation, endStation) to a list storing total travel time and number of trips.
- When a customer checks in, we record the station and time in the check-in dictionary.
- Upon check out, we calculate the travel time and update the route dictionary with the accumulated travel time and increment the trip count.
- Average time computation simply takes the total time divided by the number of trips from the route dictionary.
class UndergroundSystem:
def __init__(self):
self.checkInData = {}
self.routeData = {}
def checkIn(self, id: int, stationName: str, t: int):
self.checkInData[id] = (stationName, t)
def checkOut(self, id: int, stationName: str, t: int):
startStation, startTime = self.checkInData.pop(id)
route = (startStation, stationName)
travelTime = t - startTime
if route not in self.routeData:
self.routeData[route] = [0, 0]
self.routeData[route][0] += travelTime
self.routeData[route][1] += 1
def getAverageTime(self, startStation: str, endStation: str) -> float:
totalTime, count = self.routeData[(startStation, endStation)]
return totalTime / count#include <unordered_map>
#include <string>
#include <utility>
using namespace std;
class UndergroundSystem {
private:
unordered_map<int, pair<string, int>> checkInData;
unordered_map<string, pair<int, int>> routeData;
public:
UndergroundSystem() {}
void checkIn(int id, const string &stationName, int t) {
checkInData[id] = {stationName, t};
}
void checkOut(int id, const string &stationName, int t) {
auto &checkInInfo = checkInData[id];
string routeKey = checkInInfo.first + "->" + stationName;
int travelTime = t - checkInInfo.second;
checkInData.erase(id);
if (routeData.find(routeKey) == routeData.end()) {
routeData[routeKey] = {0, 0};
}
routeData[routeKey].first += travelTime;
routeData[routeKey].second += 1;
}
double getAverageTime(const string &startStation, const string &endStation) {
string routeKey = startStation + "->" + endStation;
auto &routeInfo = routeData[routeKey];
return (double) routeInfo.first / routeInfo.second;
}
};class UndergroundSystem {
constructor() {
this.checkInData = new Map();
this.routeData = new Map();
}
checkIn(id, stationName, t) {
this.checkInData.set(id, { stationName, t });
}
checkOut(id, stationName, t) {
const { stationName: startStation, t: startTime } = this.checkInData.get(id);
this.checkInData.delete(id);
const routeKey = startStation + '->' + stationName;
const travelTime = t - startTime;
if (!this.routeData.has(routeKey)) {
this.routeData.set(routeKey, { totalTime: 0, tripCount: 0 });
}
const routeInfo = this.routeData.get(routeKey);
routeInfo.totalTime += travelTime;
routeInfo.tripCount += 1;
this.routeData.set(routeKey, routeInfo);
}
getAverageTime(startStation, endStation) {
const routeKey = startStation + '->' + endStation;
const { totalTime, tripCount } = this.routeData.get(routeKey);
return totalTime / tripCount;
}
}The Python solution uses two dictionaries, checkInData and routeData, to track check-in information and route statistics, respectively. The checkIn function stores the check-in details by mapping the ID to the station name and time. The checkOut function calculates travel time, updates the route statistics in routeData, and removes the check-in record for the customer. Finally, getAverageTime computes and returns the average travel time for the specified route.
Time Complexity: O(1) for each operation (check-in, check-out, and get average time) because dictionary operations are constant time.
Space Complexity: O(P + R) where P is the number of passengers and R is the number of route pairs.
Approach 2: List Method with String Keys
This method uses a list and constructs a unique key using the combination of start and end stations for storing travel information.
- Maintain a dictionary to store each passenger's check-in information.
- Maintain another dictionary to keep track of (start, end) station journeys using a string as a key.
- For each journey, store total time and total trips for that route in the dictionary.
- Calculate average using total time and trips upon request.
import java.util.HashMap;
class UndergroundSystem {
private HashMap<Integer, CheckInData> checkInMap;
private HashMap<String, RouteData> routeMap;
class CheckInData {
String stationName;
int time;
CheckInData(String stationName, int time) {
this.stationName = stationName;
this.time = time;
}
}
class RouteData {
int totalTime;
int tripCount;
RouteData() {
this.totalTime = 0;
this.tripCount = 0;
}
}
public UndergroundSystem() {
this.checkInMap = new HashMap<>();
this.routeMap = new HashMap<>();
}
public void checkIn(int id, String stationName, int t) {
checkInMap.put(id, new CheckInData(stationName, t));
}
public void checkOut(int id, String stationName, int t) {
CheckInData checkInData = checkInMap.get(id);
String routeKey = checkInData.stationName + "->" + stationName;
int travelTime = t - checkInData.time;
checkInMap.remove(id);
RouteData routeData = routeMap.getOrDefault(routeKey, new RouteData());
routeData.totalTime += travelTime;
routeData.tripCount += 1;
routeMap.put(routeKey, routeData);
}
public double getAverageTime(String startStation, String endStation) {
String routeKey = startStation + "->" + endStation;
RouteData routeData = routeMap.get(routeKey);
return (double) routeData.totalTime / routeData.tripCount;
}
}#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define HASH_SIZE 10000
typedef struct CheckInData {
char stationName[11];
int time;
} CheckInData;
typedef struct RouteData {
int totalTime;
int tripCount;
struct RouteData *next;
} RouteData;
typedef struct HashTable {
CheckInData *checkInEntries[HASH_SIZE];
RouteData *routeEntries[HASH_SIZE];
} HashTable;
unsigned int hash(char *s) {
unsigned int hash = 0;
while (*s) hash = (hash * 101 + *s++) % HASH_SIZE;
return hash;
}
HashTable* createTable() {
HashTable* ht = (HashTable*) malloc(sizeof(HashTable));
for (int i = 0; i < HASH_SIZE; i++) {
ht->checkInEntries[i] = NULL;
ht->routeEntries[i] = NULL;
}
return ht;
}
void checkIn(HashTable *ht, int id, char *stationName, int t) {
CheckInData *checkInData = (CheckInData*) malloc(sizeof(CheckInData));
strcpy(checkInData->stationName, stationName);
checkInData->time = t;
ht->checkInEntries[id % HASH_SIZE] = checkInData;
}
void checkOut(HashTable *ht, int id, char *stationName, int t) {
unsigned int index = id % HASH_SIZE;
CheckInData *checkInData = ht->checkInEntries[index];
char routeKey[23];
snprintf(routeKey, 23, "%s->%s", checkInData->stationName, stationName);
unsigned int hashIndex = hash(routeKey);
RouteData *routeData = ht->routeEntries[hashIndex];
int travelTime = t - checkInData->time;
while (routeData && strcmp(routeKey, routeData + 1)) {
routeData = routeData->next;
}
if (!routeData) {
routeData = (RouteData *) malloc(sizeof(RouteData) + 24);
strcpy((char *)(routeData + 1), routeKey);
routeData->totalTime = 0;
routeData->tripCount = 0;
routeData->next = ht->routeEntries[hashIndex];
ht->routeEntries[hashIndex] = routeData;
}
routeData->totalTime += travelTime;
routeData->tripCount += 1;
free(checkInData);
ht->checkInEntries[index] = NULL;
}
double getAverageTime(HashTable *ht, char *startStation, char *endStation) {
char routeKey[23];
snprintf(routeKey, 23, "%s->%s", startStation, endStation);
unsigned int hashIndex = hash(routeKey);
RouteData *routeData = ht->routeEntries[hashIndex];
while (routeData && strcmp(routeKey, routeData + 1)) {
routeData = routeData->next;
}
if (routeData) {
return (double) routeData->totalTime / routeData->tripCount;
}
return -1.0; // should never reach here by constraint
}
int main() {
HashTable *system = createTable();
checkIn(system, 1, "Leyton", 10);
checkOut(system, 1, "Waterloo", 20);
checkIn(system, 2, "Leyton", 15);
checkOut(system, 2, "Waterloo", 25);
printf("Average Time: %.2f\n", getAverageTime(system, "Leyton", "Waterloo"));
return 0;
}The Java solution utilizes helper classes, CheckInData and RouteData, to encapsulate the requisite data. The main class, UndergroundSystem, manages check-ins using checkInMap, mapping customer IDs to CheckInData. The check-out data is stored in routeMap, where travel information for each route is updated using RouteData. The average time is computed directly when requested.
Time Complexity: O(1) for all operations due to constant time performance of the HashMap.
Space Complexity: O(P + R), where P represents the checked-in passengers, and R is the number of unique routes.
Approach 3: Hash Table
We use two hash tables to store data:
ts: Stores the passenger's id, check-in time, and check-in station. The key is the passenger's id, and the value is a tuple(t, stationName).d: Stores the passenger's check-in station, check-out station, travel time, and number of trips. The key is a tuple(startStation, endStation), and the value is a tuple(totalTime, count).
When a passenger checks in, we store the passenger's id, check-in time, and check-in station in ts, i.e., ts[id] = (t, stationName).
When a passenger checks out, we retrieve the passenger's check-in time and station (t0, station) from ts, then calculate the passenger's travel time t - t_0, and store the passenger's travel time and number of trips in d.
When we want to calculate a passenger's average travel time, we retrieve the passenger's total travel time and number of trips (totalTime, count) from d, then calculate the average travel time as totalTime / count.
The time complexity is O(1), and the space complexity is O(n). Where n is the number of passengers.
type UndergroundSystem struct {
ts map[int]pair
d map[station][2]int
}
func Constructor() UndergroundSystem {
return UndergroundSystem{
ts: make(map[int]pair),
d: make(map[station][2]int),
}
}
func (this *UndergroundSystem) CheckIn(id int, stationName string, t int) {
this.ts[id] = pair{t, stationName}
}
func (this *UndergroundSystem) CheckOut(id int, stationName string, t int) {
p := this.ts[id]
s := station{p.a, stationName}
if _, ok := this.d[s]; !ok {
this.d[s] = [2]int{t - p.t, 1}
} else {
this.d[s] = [2]int{this.d[s][0] + t - p.t, this.d[s][1] + 1}
}
}
func (this *UndergroundSystem) GetAverageTime(startStation string, endStation string) float64 {
s := station{startStation, endStation}
return float64(this.d[s][0]) / float64(this.d[s][1])
}
type station struct {
a string
b string
}
type pair struct {
t int
a string
}
/**
* Your UndergroundSystem object will be instantiated and called as such:
* obj := Constructor();
* obj.CheckIn(id,stationName,t);
* obj.CheckOut(id,stationName,t);
* param_3 := obj.GetAverageTime(startStation,endStation);
*/Complexity comparison
| Approach | Complexity |
|---|---|
| Two Dictionary Method | Time Complexity: |
| List Method with String Keys | Time Complexity: |
| Hash Table | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Two Dictionary Method | O(1) per operation | O(n) | Standard solution for interviews and scalable production-style design |
| List Method with String Keys | O(1) per operation | O(n) | Useful when composite map keys are inconvenient and string keys are simpler |
Frequently asked questions
Is Design Underground System easy or hard?
Design Underground System is generally rated Medium. The logic is straightforward once you recognize the need for two hash maps, but the problem evaluates your ability to design a clean data model and maintain efficient constant-time operations.
Design Underground System Python/Java solution
Python and Java implementations both rely on hash maps. Python typically uses dictionaries with tuple keys, while Java may use HashMap with concatenated string keys or custom pair objects. The algorithmic logic remains the same: store active check-ins and aggregate travel durations.
How to solve Design Underground System in O(1)?
Maintain two hash tables: one mapping passenger IDs to their check-in station and time, and another mapping station pairs to total travel time and trip count. When a passenger checks out, compute the trip duration and update the aggregated statistics. Average travel time becomes a constant-time division of total time by trip count.
What is the best approach for Design Underground System?
The best approach uses two hash maps. One map stores active trips by passenger ID, while the second stores aggregated statistics for each station pair. This allows check-in, check-out, and average time queries to run in O(1) time with O(n) space for stored trip data.
Is Design Underground System asked at Google/Amazon/Meta?
Design-style data structure problems like this frequently appear in interviews at companies such as Amazon, Google, and Meta. The question tests your ability to design efficient data storage, maintain running aggregates, and implement constant-time operations using hash maps.
What data structure is used in Design Underground System?
The core data structure is a hash table. One hash map tracks active trips by passenger ID, while another aggregates travel statistics by station pair. Some implementations also use strings as composite keys for station pairs.
What is the time complexity of Design Underground System?
Each operation—checkIn, checkOut, and getAverageTime—runs in O(1) time using hash table lookups and updates. Space complexity is O(n), where n is the number of passengers or unique station pairs stored in the system.
