#2353
Design a Food Rating System
MediumArrayHash TableStringDesignHeap (Priority Queue)Ordered SetHash MapPriority Queue
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(log n) for changeRating and O(1) for highestRated. |
| Space | O(1) | O(n) |
💡
Intuition
Time O(log n) for changeRating and O(1) for highestRated.Space O(n)
In this approach, we will use a combination of a hash map and a max heap (priority queue) to efficiently manage food ratings and quickly retrieve the highest-rated food for a given cuisine.
⚙️
Algorithm
4 steps- 1Step 1: Use a hash map to map each food to its current rating and cuisine.
- 2Step 2: Use a max heap (priority queue) to maintain the highest-rated food items for each cuisine.
- 3Step 3: For changeRating, update the rating in the hash map and reinsert the food into the heap to maintain order.
- 4Step 4: For highestRated, simply retrieve the top of the heap for the specified cuisine.
solution.py26 lines
1import heapq
2
3class FoodRatings:
4 def __init__(self, foods, cuisines, ratings):
5 self.food_map = {}
6 self.cuisine_map = {}
7 self.cuisine_heap = {}
8
9 for food, cuisine, rating in zip(foods, cuisines, ratings):
10 self.food_map[food] = rating
11 self.cuisine_map[food] = cuisine
12 if cuisine not in self.cuisine_heap:
13 self.cuisine_heap[cuisine] = []
14 heapq.heappush(self.cuisine_heap[cuisine], (-rating, food))
15
16 def changeRating(self, food, newRating):
17 cuisine = self.cuisine_map[food]
18 self.food_map[food] = newRating
19 heapq.heappush(self.cuisine_heap[cuisine], (-newRating, food))
20
21 def highestRated(self, cuisine):
22 while self.cuisine_heap[cuisine]:
23 rating, food = self.cuisine_heap[cuisine][0]
24 if -rating == self.food_map[food]:
25 return food
26 heapq.heappop(self.cuisine_heap[cuisine])ℹ
Complexity note: The complexity is efficient because we only need to maintain a heap for each cuisine, allowing us to quickly access and update the highest-rated food.
- 1Using a hash map allows for O(1) access to food ratings.
- 2A max heap efficiently keeps track of the highest-rated food.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.