MediumNo. 2353
Design a Food Rating System — LeetCode 2353 Python Solution
- Pattern
- Heap / Priority Queue
- Topics
- Design, Array, Hash Table, String, Ordered Set, Heap (Priority Queue)
- Reading time
- 5 min
- Source
- leetcode.com
The problem
Design a food rating system that can do the following: Modify the rating of a food item listed in the system. Return the highest-rated food item for a type of cuisine in the system.
Example
- Input
- ["FoodRatings", "highestRated", "highestRated", "changeRating", "highestRated", "changeRating", "highestRated"]
- Output
- [null, "kimchi", "ramen", null, "sushi", null, "ramen"]
- Explanation
- FoodRatings foodRatings = new FoodRatings(["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]);
Python solution
class FoodRatings:
def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
self.d = defaultdict(SortedList)
self.g = {}
for food, cuisine, rating in zip(foods, cuisines, ratings):
self.d[cuisine].add((-rating, food))
self.g[food] = (rating, cuisine)
def changeRating(self, food: str, newRating: int) -> None:
oldRating, cuisine = self.g[food]
self.g[food] = (newRating, cuisine)
self.d[cuisine].remove((-oldRating, food))
self.d[cuisine].add((-newRating, food))
def highestRated(self, cuisine: str) -> str:
return self.d[cuisine][0][1]
# Your FoodRatings object will be instantiated and called as such:
# obj = FoodRatings(foods, cuisines, ratings)
# obj.changeRating(food,newRating)
# param_2 = obj.highestRated(cuisine)Complexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2353. Design a Food Rating System is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1912 | Design Movie Rental System | Hard |
| 2349 | Design a Number Container System | Medium |
| 0692 | Top K Frequent Words | Medium |
| 0745 | Prefix and Suffix Search | Hard |
| 1348 | Tweet Counts Per Frequency | Medium |
| 1418 | Display Table of Food Orders in a Restaurant | Medium |
Frequently asked questions
- How hard is LeetCode 2353. Design a Food Rating System?
LeetCode 2353. Design a Food Rating System is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2353. Design a Food Rating System?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2353. Design a Food Rating System?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2353. Design a Food Rating System cover?
LeetCode 2353. Design a Food Rating System is tagged Design, Array, Hash Table, String, Ordered Set and Heap (Priority Queue) on LeetCode.