Design a Food Rating System - Solution
Solutions and explanations
class FoodRatings:
def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
self.food_info = {} # food : [cuisine, current rating]
self.cuisine_heaps = collections.defaultdict(list) # cuisine : max_heap with lazy deletion
for idx, food in enumerate(foods):
self.food_info[food] = [cuisines[idx], ratings[idx]]
heapq.heappush(self.cuisine_heaps[cuisines[idx]], (-ratings[idx], food))
def changeRating(self, food: str, new_rating: int) -> None:
self.food_info[food][1] = new_rating
cuisine = self.food_info[food][0]
heapq.heappush(self.cuisine_heaps[cuisine], (-new_rating, food))
def highestRated(self, cuisine: str) -> str:
max_heap = self.cuisine_heaps[cuisine]
# Lazy Deletion: Pop until the rating at top matches the current rating
while max_heap:
top = max_heap[0] # (-rating, food)
rating, food = -top[0], top[1]
if rating == self.food_info[food][1] and cuisine == self.food_info[food][0]:
return food
heapq.heappop(max_heap)
return ""
# 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 Analysis
Here, n is the number of food items.
Initialization:
- Time Complexity:
O(n log n)- Each push to the heap takes
O(log n)time, and each of thenfoods is pushed into a heap. So, overall takesO(log n)time.
- Each push to the heap takes
- Space Complexity:
O(n)space for the hashmaps.- One hashmap for storing the food info of size
n(one entry per food). - Another hashmap for storing the max heaps for each cuisine, together holding
nentries.
- One hashmap for storing the food info of size
Change Rating
- Time Complexity:
O(log n)- Updating the food rating in the hashmap takes
O(1)time, and pushing into the heap takesO(log n).
- Updating the food rating in the hashmap takes
- Space Complexity:
O(1)- Only a new entry is pushed into the heap. (Overall extra space stays proportional to existing entries.)
Hightest Rating:
- Time Complexity:
O(log n)amortized- Each time it may pop stale entries, but since each outdated rating can only be removed once, the amortized cost per call is
O(log n).
- Each time it may pop stale entries, but since each outdated rating can only be removed once, the amortized cost per call is
- Space Complexity:
O(1)- No additional data structures are used apart from temporary variables.