leetcode

Design a Food Rating System - Link

Question Description

Design a food rating system that can do the following:

Implement the FoodRatings class:


Constraints


Approach

Use three maps:

  1. foodCuisines: Maps food → cuisine
  2. foodRating: Maps food → rating
  3. cuisinesRatingFood: Maps cuisine → TreeSet of pairs (-rating, foodName)

Store ratings as negative in the TreeSet, so the highest-rated food is always the first element (TreeSet sorts in ascending order, so -10 comes before -5).

Why this approach works:

Alternative approaches considered:


Dry Run

Example Input:

foods = ["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"]
cuisines = ["korean", "japanese", "japanese", "greek", "japanese", "korean"]
ratings = [9, 12, 8, 15, 14, 7]

Step-by-step execution:

Final Answer = "ramen"


Solution

import javafx.util.Pair;
import java.util.*;

public class FoodRatings {

    private Map<String, TreeSet<Pair<Integer, String>>> cuisinesRatingFood = new HashMap<>();
    private Map<String, String> foodCuisines = new HashMap<>();
    private Map<String, Integer> foodRating = new HashMap<>();

    public FoodRatings(String[] foods, String[] cuisines, int[] ratings) {
        for (int i = 0; i < foods.length; ++i) {
            foodCuisines.put(foods[i], cuisines[i]);
            foodRating.put(foods[i], ratings[i]);

            cuisinesRatingFood.computeIfAbsent(cuisines[i], e -> new TreeSet<>(
                    (a, b) -> a.getKey().equals(b.getKey()) 
                        ? a.getValue().compareTo(b.getValue()) 
                        : Integer.compare(a.getKey(), b.getKey())))
                    .add(new Pair<>(-ratings[i], foods[i]));
        }
    }

    public void changeRating(String food, int newRating) {
        int oldRating = foodRating.get(food);

        TreeSet<Pair<Integer, String>> cuisineSet = cuisinesRatingFood.get(foodCuisines.get(food));
        cuisineSet.remove(new Pair<>(-oldRating, food));

        foodRating.put(food, newRating);
        cuisineSet.add(new Pair<>(-newRating, food));
    }

    public String highestRated(String cuisine) {
        return cuisinesRatingFood.get(cuisine).first().getValue();
    }
}

Time and Space Complexity