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 with three methods:

A trip from one station to another is a different route from the trip back.

Example
checkIn(45, "Hill", 3), checkIn(32, "Bridge", 8), checkIn(27, "Hill", 10)
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
Solution

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: checkIn is the first tap and checkOut the second. From them it has to tell how long a trip from one station to another takes on average.

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). It names the card, the station it left and the time. It does not say where or when the card entered; that came in an earlier call. So how can checkOut know the trip took 12?

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 open, for the cards travelling now, and totals, with one row per route. It shows them just before card 10 checks out.

checkOut(10, "Park", 38) removes card 10 from open, where it was recorded as entering Hill at time 24. The trip time, 14, is added to the Hill to Park row of totals, which goes from total 22 over 2 trips to 36 over 3 trips, an average of 12.0.

Look at the picture. checkOut(10, "Park", 38) first finds card 10 in open: it entered Hill at time 24. The trip is over, so that row is removed. The trip time, 38 - 24 = 14, then goes into the Hill → Park row of totals. The total grows from 22 to 36 and the trips from 2 to 3, so the average is 36 / 3 = 12.0, the last answer in the example.

The third answer, 11.0, came while card 10 was still in open. A trip only counts once the card has checked out.

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 checkOut find the check-in? In a HashMap from card id to the station and time of the check-in. checkIn adds an entry, and checkOut looks it up and removes it in one step.

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 find the row for Hill → Park? The key must hold both stations, in order, because Hill → Park and Park → Hill are different routes.

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 "->" between the names fixes that, as long as no station name contains it.

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 equals and hashCode based on those values, so two Route("Hill", "Park") objects count as the same key in a 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 call adds up a million numbers. A total and a count give the same average with one division.

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 gives the newest trip half the weight: trips of 10, 20 and 30 come out as 22.5, while their real average is 20.

The total is a long, not an int. Trip times can be large and trips many: 3,000 trips of 1,000,000 each add up to 3,000,000,000, more than the largest int, 2,147,483,647. An int total would wrap around to -1,294,967,296.

The division happens in double, because averages are often not whole numbers. In Java, 21 / 2 on two whole numbers gives 10, while (double) 21 / 2 gives 10.5.

Java Solution

The class has these parts:

  • CheckIn: a record of the station and time of one check-in.
  • Route: a record of a start and an end station, the key of totals.
  • open: the table of cards travelling now, from card id to its CheckIn.
  • totals: the table of routes, from Route to an array of two long values, the total time and the number of trips.
  • checkOut: removes the card from open and adds the trip to its route. computeIfAbsent creates the route's array the first time the route is seen.
  • getAverageTime: divides the route's total by its trips, as a double.

The main method runs the example, then sends card 45 back from Park to Hill, adds a fourth Hill → Park trip, and makes 3,000 long trips on a new route.

Java
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:

Output
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 division keeps the .25.

The last line is the route with 3,000 trips of 1,000,000. Their total, 3,000,000,000, fits in the long, so the average comes out exactly 1000000.0.

The original implementation, UndergroundSystem.java, is on GitHub.

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 HashMap lookup takes one step on average, but finding a Route key computes the hash codes of both names, which reads every character. Station names are short, so this stays small.
  • Space: O(P + R), for P cards travelling now and R routes seen. open holds one entry per card that has checked in but not out, and totals holds two numbers per route, however many trips it has.