- 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
- 52 lines of Java from the credited upstream file 1912.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 1 loop block 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 MovieRentingSystem {2 public MovieRentingSystem(int n, int[][] entries) {3 for (int[] e : entries) {4 final int shop = e[0];5 final int movie = e[1];6 final int price = e[2];7 unrented.putIfAbsent(movie, new TreeSet<>(comparator));8 unrented.get(movie).add(new Entry(price, shop, movie));9 shopAndMovieToPrice.put(new Pair<>(shop, movie), price);10 }11 }12 13 public List<Integer> search(int movie) {14 return unrented.getOrDefault(movie, Collections.emptySet())15 .stream()16 .limit(5)17 .map(e -> e.shop)18 .collect(Collectors.toList());19 }20 21 public void rent(int shop, int movie) {22 final int price = shopAndMovieToPrice.get(new Pair<>(shop, movie));23 unrented.get(movie).remove(new Entry(price, shop, movie));24 rented.add(new Entry(price, shop, movie));25 }26 27 public void drop(int shop, int movie) {28 final int price = shopAndMovieToPrice.get(new Pair<>(shop, movie));29 unrented.get(movie).add(new Entry(price, shop, movie));30 rented.remove(new Entry(price, shop, movie));31 }32 33 public List<List<Integer>> report() {34 return rented.stream().limit(5).map(e -> List.of(e.shop, e.movie)).collect(Collectors.toList());35 }36 37 private record Entry(int price, int shop, int movie) {}38 39 private Comparator<Entry> comparator = Comparator.comparingInt(Entry::price)40 .thenComparingInt(Entry::shop)41 .thenComparingInt(Entry::movie);42 43 44 private Map<Integer, Set<Entry>> unrented = new HashMap<>();45 46 47 private Map<Pair<Integer, Integer>, Integer> shopAndMovieToPrice = new HashMap<>();48 49 50 private Set<Entry> rented = new TreeSet<>(comparator);51}52