- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 41 lines of Java from the credited upstream file 1396.java.
- The implementation visibly relies on hash lookup, ordered lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class CheckIn {2 public String stationName;3 public int time;4 public CheckIn(String stationName, int time) {5 this.stationName = stationName;6 this.time = time;7 }8}9 10class CheckOut {11 public int numTrips;12 public int totalTime;13 public CheckOut(int numTrips, int totalTime) {14 this.numTrips = numTrips;15 this.totalTime = totalTime;16 }17}18 19class UndergroundSystem {20 public void checkIn(int id, String stationName, int t) {21 checkIns.put(id, new CheckIn(stationName, t));22 }23 24 public void checkOut(int id, String stationName, int t) {25 final CheckIn checkIn = checkIns.get(id);26 checkIns.remove(id);27 final String route = checkIn.stationName + "->" + stationName;28 checkOuts.putIfAbsent(route, new CheckOut(0, 0));29 ++checkOuts.get(route).numTrips;30 checkOuts.get(route).totalTime += t - checkIn.time;31 }32 33 public double getAverageTime(String startStation, String endStation) {34 final CheckOut checkOut = checkOuts.get(startStation + "->" + endStation);35 return checkOut.totalTime / (double) checkOut.numTrips;36 }37 38 private Map<Integer, CheckIn> checkIns = new HashMap<>(); 39 private Map<String, CheckOut> checkOuts = new HashMap<>(); 40}41