Design a Food Rating System (LeetCode 2353): Solution and Explanation

Medium
Design
Heap
Hash Table
Ordered Set

Support rating changes and return the best-rated food of a cuisine, breaking ties by the lexicographically smaller name.

Intuition

highestRated asks for a maximum inside one cuisine, which is what a heap per cuisine gives you, ordered by rating first and name second.

The trouble is changeRating: a heap cannot find and update an entry in the middle. Instead of updating, push a fresh (rating, food) entry and leave the old one where it is.

An old entry is easy to recognise later, because its rating no longer matches the rating map. Only the top of the heap matters, so stale entries are thrown away only when they surface.

Approach: Heap per cuisine with lazy deletion

  1. Keep rating[food], cuisine[food], and for every cuisine a heap of (-rating, food) pairs.
  2. Constructor: fill both maps and push every food onto its cuisine's heap.
  3. changeRating(food, r): set rating[food] = r and push (-r, food) onto heap[cuisine[food]].
  4. highestRated(c): while the top pair's rating differs from rating[top food], pop it. Return the top food.

Step-by-step example

foods = [kimchi, miso, sushi, moussaka, ramen, bulgogi], ratings = [9, 12, 8, 15, 14, 7]
  1. The korean heap holds kimchi 9 and bulgogi 7; the japanese heap holds ramen 14, miso 12, sushi 8; the greek heap holds moussaka 15.
  2. highestRated(korean): the top kimchi 9 matches its rating, return kimchi.
  3. highestRated(japanese): the top ramen 14 is current, return ramen.
  4. changeRating(sushi, 16): push sushi 16. The old sushi 8 stays inside, now stale.
  5. highestRated(japanese): sushi 16 is on top and current, return sushi.
  6. changeRating(ramen, 16): push ramen 16. It ties sushi 16, and ramen < sushi, so ramen 16 becomes the top.
  7. highestRated(japanese): return ramen. Output: [null, kimchi, ramen, null, sushi, null, ramen].

Code: Python, Java, C++

1class FoodRatings:
2    def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
3        self.rating = {}
4        self.cuisine = {}
5        self.heaps = {}
6        for food, cuisine, rating in zip(foods, cuisines, ratings):
7            self.rating[food] = rating
8            self.cuisine[food] = cuisine
9            heapq.heappush(self.heaps.setdefault(cuisine, []), (-rating, food))
10
11    def changeRating(self, food: str, newRating: int) -> None:
12        self.rating[food] = newRating
13        heapq.heappush(self.heaps[self.cuisine[food]], (-newRating, food))
14
15    def highestRated(self, cuisine: str) -> str:
16        heap = self.heaps[cuisine]
17        while -heap[0][0] != self.rating[heap[0][1]]:
18            heapq.heappop(heap)
19        return heap[0][1]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(log(n + q)) amortized per call

Each call pushes at most one entry, and each entry is popped at most once over the whole run.

Space

O(n + q)

Every changeRating adds one entry that may linger until it reaches the top.

Other approaches

Ordered set per cuisine (time O(log n) per call, space O(n))

Keep a balanced BST (TreeSet, std::set, SortedSet) of (-rating, name) per cuisine. changeRating removes the old pair and inserts the new one, so no stale entries ever exist.

Scan the cuisine (time O(n) per highestRated, space O(n))

Store foods per cuisine and scan them all in highestRated. Simple, but O(n) per query is too slow for 2 * 10^4 calls on 2 * 10^4 foods.

Common mistakes

  • Comparing only ratings and forgetting the name tie-break, or ordering names in the wrong direction while ratings are reversed for a min-heap.
  • Trying to update the rating inside an existing heap entry, which breaks the heap order.
  • Checking staleness by food name only. An entry is stale when its stored rating differs from the current rating, not merely because the food was changed once.
  • Using a locale-aware string compare (C# string.Compare) instead of an ordinal one for the tie-break.

Frequently asked questions

What if a food's rating goes back to an old value?

Then an older entry with that same rating matches the map again. That is fine: it describes the food exactly as it is now, so returning it is correct, and any duplicate is popped later or never reached.

Can the heaps grow without bound?

They grow by one entry per changeRating, so at most n + q entries in total. That is within the limits; if memory mattered you could rebuild a heap when stale entries outnumber live ones.

Why does the C# solution use SortedSet?

The judge runs .NET 5, which has no PriorityQueue class. A SortedSet ordered by (-rating, name) acts as the heap: Min is the top and Remove(Min) is the pop.