Problem Description
Design a system to manage food items where each food has a name, a type of cuisine, and a rating. The system must allow updating a food's rating and efficiently returning the highest-rated food for a given cuisine. When two foods have the same rating, the one with the lexicographically smaller name should be returned.
Key Insights
- Use a hash map to store each food's current rating and cuisine.
- Maintain a max heap for each cuisine to retrieve the highest-rated food quickly.
- Store tuples of (-rating, food) in the heap. The negative rating turns the min-heap (default in many languages) into a max-heap.
- Handle rating updates with lazy deletion: insert the updated rating into the heap and, during retrieval, discard stale entries whose rating does not match the latest value in the hash map.
- Lexicographical order is naturally supported by storing the food name in the tuple and relying on tuple comparison.
Space and Time Complexity
Time Complexity:
- changeRating: O(log n) due to heap insertion.
- highestRated: O(log n) amortized as stale entries are lazily removed from the heap.
Space Complexity: O(n) for storing the maps and heaps.
Solution
We create three primary data structures:
- A map from food to its current rating (foodToRating).
- A map from food to its cuisine (foodToCuisine).
- A map from cuisine to a max heap (cuisineToHeap) that stores pairs of (-rating, food).
When a food’s rating is updated, we update the foodToRating map and push the new (-rating, food) tuple onto the appropriate heap. When a query for the highest-rated food is made, we repeatedly check the top of the heap for that cuisine. If the top entry’s rating (after sign inversion) matches the current rating in foodToRating, it is returned; otherwise, we pop the stale value and continue. This lazy deletion avoids the overhead of directly removing outdated entries from the heap.