- 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
- 33 lines of Java from the credited upstream file 2353.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 FoodRatings {2 public FoodRatings(String[] foods, String[] cuisines, int[] ratings) {3 for (int i = 0; i < foods.length; ++i) {4 cuisineToRatingAndFoods.putIfAbsent(5 cuisines[i],6 new TreeSet<>(7 Comparator.comparing(Pair<Integer, String>::getKey, Comparator.reverseOrder())8 .thenComparing(Pair<Integer, String>::getValue)));9 cuisineToRatingAndFoods.get(cuisines[i]).add(new Pair<>(ratings[i], foods[i]));10 foodToCuisine.put(foods[i], cuisines[i]);11 foodToRating.put(foods[i], ratings[i]);12 }13 }14 15 public void changeRating(String food, int newRating) {16 final String cuisine = foodToCuisine.get(food);17 final int oldRating = foodToRating.get(food);18 TreeSet<Pair<Integer, String>> ratingAndFoods = cuisineToRatingAndFoods.get(cuisine);19 ratingAndFoods.remove(new Pair<>(oldRating, food));20 ratingAndFoods.add(new Pair<>(newRating, food));21 foodToRating.put(food, newRating);22 }23 24 public String highestRated(String cuisine) {25 return cuisineToRatingAndFoods.get(cuisine).first().getValue();26 }27 28 29 Map<String, TreeSet<Pair<Integer, String>>> cuisineToRatingAndFoods = new HashMap<>();30 Map<String, String> foodToCuisine = new HashMap<>();31 Map<String, Integer> foodToRating = new HashMap<>();32}33