- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 26 lines of Python from the credited upstream file 2353.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from sortedcontainers import SortedSet2 3 4class FoodRatings:5 def __init__(self, foods: list[str], cuisines: list[str], ratings: list[int]):6 self.cuisineToRatingAndFoods = collections.defaultdict(7 lambda: SortedSet(key=lambda x: (-x[0], x[1])))8 self.foodToCuisine = {}9 self.foodToRating = {}10 11 for food, cuisine, rating in zip(foods, cuisines, ratings):12 self.cuisineToRatingAndFoods[cuisine].add((rating, food))13 self.foodToCuisine[food] = cuisine14 self.foodToRating[food] = rating15 16 def changeRating(self, food: str, newRating: int) -> None:17 cuisine = self.foodToCuisine[food]18 oldRating = self.foodToRating[food]19 ratingAndFoods = self.cuisineToRatingAndFoods[cuisine]20 ratingAndFoods.remove((oldRating, food))21 ratingAndFoods.add((newRating, food))22 self.foodToRating[food] = newRating23 24 def highestRated(self, cuisine: str) -> str:25 return self.cuisineToRatingAndFoods[cuisine][0][1]26