Sponsored
Sponsored
This approach involves using dictionaries (or hash maps) to store and manage the relationships between foods, cuisines, and their ratings. We will have multiple dictionaries to efficiently perform update and retrieval operations.
Time Complexity: O(N log N) for initialization and O(F log F) for changing rating where N is the number of foods and F is the list of foods for a cuisine.
Space Complexity: O(N) for storage of mappings.
1class FoodRatings:
2 def __init__(self, foods: [str], cuisines: [str], ratings: [int]):
3 self.food_to_cuisine = {food: cuisine for food, cuisine in zip(foods, cuisines)}
4 self.food_to_rating = {food: rating for food, rating in zip(foods, ratings)}
5 self.cuisine_to_foods = {}
6 for food, cuisine, rating in zip(foods, cuisines, ratings):
7 if cuisine not in self.cuisine_to_foods:
8 self.cuisine_to_foods[cuisine] = []
9 self.cuisine_to_foods[cuisine].append((-rating, food))
10 for cuisine in self.cuisine_to_foods:
11 self.cuisine_to_foods[cuisine].sort()
12
13 def changeRating(self, food: str, newRating: int) -> None:
14 old_rating = self.food_to_rating[food]
15 self.food_to_rating[food] = newRating
16 cuisine = self.food_to_cuisine[food]
17 self.cuisine_to_foods[cuisine] = [(-self.food_to_rating[fd], fd) if fd == food else fr
18 for fr in self.cuisine_to_foods[cuisine]]
19 self.cuisine_to_foods[cuisine].sort()
20
21 def highestRated(self, cuisine: str) -> str:
22 return self.cuisine_to_foods[cuisine][0][1]
The code initializes a class with dictionaries to map each food to its corresponding cuisine and rating. Another dictionary maps cuisines to lists of foods, sorted by their negative ratings (to simulate max-heap behavior using sorting). When we change a rating, we update the corresponding entry and re-sort the list for that cuisine. For retrieving the highest-rated food, we return the first item in the sorted list.
This approach uses priority queues (heaps) to manage the highest-rated food for a cuisine. Heaps offer efficient operations for maintaining and retrieving maximum values, which can be useful for finding the highest-rated item.
Time Complexity: O(N) for initialization and O(log F) for updating heap or retrieving the maximum where F is the number of foods for given cuisine.
Space Complexity: O(N) for storing the heap elements.
1import heapq
2
3class FoodRatings:
4
The Python version uses a heap to maintain the highest-rated food for each cuisine. Negative ratings are stored to utilize the min-heap structure for max-heap behavior. If ratings change, old entries may remain invalid due to imposition of new valid values. Therefore, we remove these as necessary during the highestRated check.