Design Underground System
Record when cards enter and leave stations, and report the average trip time between two stations.
An underground railway wants to know how long trips between its stations take. Each passenger has a card with a number, the card id. Write a class UndergroundSystem
: cardcheckIn(id, stationName, t) enters the stationid at timestationName . A card is checked in at only one station at a time.t : cardcheckOut(id, stationName, t) leaves at the stationid at timestationName .t : returns the average time of all finished trips fromgetAverageTime(startStation, endStation) tostartStation . There is always at least one such trip.endStation
A trip from one station to another is a different route from the trip back.
Example
checkOut(45, "Park", 15), checkOut(27, "Park", 20), checkOut(32, "Market", 22)
getAverageTime("Bridge", "Market") returns 14.0
getAverageTime("Hill", "Park") returns 11.0
checkIn(10, "Hill", 24)
getAverageTime("Hill", "Park") returns 11.0
checkOut(10, "Park", 38)
getAverageTime("Hill", "Park") returns 12.0
The Idea
You have probably tapped a travel card on a gate when entering a station, and again when leaving. Those two taps are all the system hears about a trip: checkIncheckOut
Follow card 45 in the example. It checks in at Hill at time 3 and checks out at Park at time 15, so its trip took 15 - 3 = 12. Card 27 makes the same trip from time 10 to time 20, which took 10. Two trips from Hill to Park, of 12 and 10, average 11.0, the second answer in the example.
Now look at what the check-out call actually gets: checkOut(45, "Park", 15)checkOut
Only if the object remembers. Each check-in has to be kept until the same card checks out. And once a trip is finished, what must be kept for the average? Not every trip. An average is the total time divided by the number of trips, so a running total and a count for each route are enough.
So the object keeps two tables. The picture calls them opentotals
Look at the picture. checkOut(10, "Park", 38)opentotals
The third answer, 11.0, came while card 10 was still in open
Solution Approach
Turning the two tables into code means settling three things: how to keep the cards still travelling, how to name a route, and what to keep for each route.
The cards still travelling
Where does checkOutHashMapcheckIncheckOut
Removing matters. A card can travel again later, and the map then holds only the cards that are travelling right now. Because a card is checked in at only one station at a time, one entry per card is enough.
The key for a route
How should totals
Joining the two names into one string looks easy, but plain joining can mix routes up: "A" + "BC" and "AB" + "C" both give "ABC". A separator such as "->"
A Java record avoids the question. A record is a short way to declare a class that only holds a few values (Java 16 and later). Java gives it equalshashCodeRoute("Hill", "Park")HashMap
What each route keeps
The simple way is to keep a list of every trip time for each route and average the list when asked. That works, but on a route with a million trips, every getAverageTime
Why not keep the average itself? Because a new trip changes it by an amount that depends on how many trips came before. Updating it as (average + trip) / 2
The total is a longintintint
The division happens in double21 / 2(double) 21 / 2
Java Solution
The class has these parts:
: a record of the station and time of one check-in.CheckIn : a record of a start and an end station, the key ofRoute .totals : the table of cards travelling now, from card id to itsopen .CheckIn : the table of routes, fromtotals to an array of twoRoute values, the total time and the number of trips.long : removes the card fromcheckOut and adds the trip to its route.open creates the route's array the first time the route is seen.computeIfAbsent : divides the route's total by its trips, as agetAverageTime .double
The main
import java.util.HashMap;
import java.util.Map;
public class UndergroundSystem {
private record CheckIn(String station, int time) { }
private record Route(String start, String end) { }
// card id -> where and when that card checked in
private final Map<Integer, CheckIn> open = new HashMap<>();
// route -> {total travel time, number of trips}
private final Map<Route, long[]> totals = new HashMap<>();
public void checkIn(int id, String stationName, int t) {
open.put(id, new CheckIn(stationName, t));
}
public void checkOut(int id, String stationName, int t) {
CheckIn in = open.remove(id); // the trip is finished
Route route = new Route(in.station(), stationName);
long[] stats = totals.computeIfAbsent(route, k -> new long[2]);
stats[0] += t - in.time(); // add this trip's time
stats[1]++; // and count it
}
public double getAverageTime(String startStation, String endStation) {
long[] stats = totals.get(new Route(startStation, endStation));
return (double) stats[0] / stats[1];
}
public static void main(String[] args) {
UndergroundSystem s = new UndergroundSystem();
s.checkIn(45, "Hill", 3);
s.checkIn(32, "Bridge", 8);
s.checkIn(27, "Hill", 10);
s.checkOut(45, "Park", 15);
s.checkOut(27, "Park", 20);
s.checkOut(32, "Market", 22);
System.out.println("Bridge -> Market: " + s.getAverageTime("Bridge", "Market"));
System.out.println("Hill -> Park: " + s.getAverageTime("Hill", "Park"));
s.checkIn(10, "Hill", 24); // still travelling
System.out.println("Hill -> Park: " + s.getAverageTime("Hill", "Park"));
s.checkOut(10, "Park", 38);
System.out.println("Hill -> Park: " + s.getAverageTime("Hill", "Park"));
// card 45 travels back, and a fourth Hill -> Park trip
s.checkIn(45, "Park", 40);
s.checkOut(45, "Hill", 70);
s.checkIn(27, "Hill", 50);
s.checkOut(27, "Park", 59);
System.out.println("Park -> Hill: " + s.getAverageTime("Park", "Hill"));
System.out.println("Hill -> Park: " + s.getAverageTime("Hill", "Park"));
// 3000 trips of 1,000,000 time units each
for (int id = 0; id < 3000; id++) {
s.checkIn(id, "Far", 0);
s.checkOut(id, "Away", 1000000);
}
System.out.println("Far -> Away: " + s.getAverageTime("Far", "Away"));
}
}
Running it prints:
Bridge -> Market: 14.0
Hill -> Park: 11.0
Hill -> Park: 11.0
Hill -> Park: 12.0
Park -> Hill: 30.0
Hill -> Park: 11.25
Far -> Away: 1000000.0
The first four lines are the example's answers. The third is still 11.0 because card 10 had only checked in; its trip of 14 shows up in the fourth line, which is 36 / 3 = 12.0.
The fifth line is card 45 again. It had checked out earlier, so it could check in at Park at time 40, and checked out at Hill at 70. Park → Hill is its own route with one trip of 30, and it did not change Hill → Park.
The sixth line adds card 27's second trip, from time 50 to 59, a trip of 9. The four Hill → Park trips add up to 12 + 10 + 14 + 9 = 45, and 45 / 4 = 11.25. The double
The last line is the route with 3,000 trips of 1,000,000. Their total, 3,000,000,000, fits in the long
The original implementation,
Complexity
Every call does at most two map operations, however many cards are travelling and however many trips are stored.
- Time: O(1) on average per call, apart from the station names. A
lookup takes one step on average, but finding aHashMap key computes the hash codes of both names, which reads every character. Station names are short, so this stays small.Route - Space: O(P + R), for P cards travelling now and R routes seen.
holds one entry per card that has checked in but not out, andopen holds two numbers per route, however many trips it has.totals