|
| 1 | +/* |
| 2 | +Problem: Design a Food Rating System |
| 3 | +LeetCode Link: https://leetcode.com/problems/design-a-food-rating-system/ |
| 4 | +
|
| 5 | +Approach: |
| 6 | +We need a data structure to: |
| 7 | +- Quickly find the highest-rated food in a given cuisine. |
| 8 | +- Efficiently update the rating of a food. |
| 9 | +
|
| 10 | +Use three maps: |
| 11 | +1. foodCuisines: Maps food → cuisine. |
| 12 | +2. foodRating: Maps food → rating. |
| 13 | +3. cuisinesRatingFood: Maps cuisine → TreeSet of pairs (-rating, foodName). |
| 14 | +
|
| 15 | +Store ratings as negative in the TreeSet, so the highest-rated food is always the first element. |
| 16 | +
|
| 17 | +On changeRating(food, newRating): |
| 18 | +- Remove the old pair (-oldRating, food). |
| 19 | +- Insert the new pair (-newRating, food). |
| 20 | +
|
| 21 | +On highestRated(cuisine): |
| 22 | +- Return the first element from the TreeSet. |
| 23 | +
|
| 24 | +Time Complexity: |
| 25 | +- Initialization: O(N log N), where N is the number of foods. |
| 26 | +- changeRating: O(log F), where F is the number of foods in the cuisine. |
| 27 | +- highestRated: O(1). |
| 28 | +
|
| 29 | +Space Complexity: |
| 30 | +O(N), where N is the number of foods. |
| 31 | +*/ |
| 32 | + |
| 33 | +import javafx.util.Pair; |
| 34 | +import java.util.*; |
| 35 | + |
| 36 | +public class FoodRatings { |
| 37 | + |
| 38 | + private Map<String, TreeSet<Pair<Integer, String>>> cuisinesRatingFood = new HashMap<>(); |
| 39 | + private Map<String, String> foodCuisines = new HashMap<>(); |
| 40 | + private Map<String, Integer> foodRating = new HashMap<>(); |
| 41 | + |
| 42 | + public FoodRatings(String[] foods, String[] cuisines, int[] ratings) { |
| 43 | + for (int i = 0; i < foods.length; ++i) { |
| 44 | + foodCuisines.put(foods[i], cuisines[i]); |
| 45 | + foodRating.put(foods[i], ratings[i]); |
| 46 | + |
| 47 | + cuisinesRatingFood.computeIfAbsent(cuisines[i], e -> new TreeSet<>( |
| 48 | + (a, b) -> a.getKey().equals(b.getKey()) |
| 49 | + ? a.getValue().compareTo(b.getValue()) |
| 50 | + : Integer.compare(a.getKey(), b.getKey()))) |
| 51 | + .add(new Pair<>(-ratings[i], foods[i])); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + public void changeRating(String food, int newRating) { |
| 56 | + int oldRating = foodRating.get(food); |
| 57 | + |
| 58 | + TreeSet<Pair<Integer, String>> cuisineSet = cuisinesRatingFood.get(foodCuisines.get(food)); |
| 59 | + cuisineSet.remove(new Pair<>(-oldRating, food)); |
| 60 | + |
| 61 | + foodRating.put(food, newRating); |
| 62 | + cuisineSet.add(new Pair<>(-newRating, food)); |
| 63 | + } |
| 64 | + |
| 65 | + public String highestRated(String cuisine) { |
| 66 | + return cuisinesRatingFood.get(cuisine).first().getValue(); |
| 67 | + } |
| 68 | +} |
0 commit comments