Sponsored
Sponsored
This approach involves using dictionaries (or hash maps) to store and manage the relationships between foods, cuisines, and their ratings. We will have multiple dictionaries to efficiently perform update and retrieval operations.
Time Complexity: O(N log N) for initialization and O(F log F) for changing rating where N is the number of foods and F is the list of foods for a cuisine.
Space Complexity: O(N) for storage of mappings.
1#include <vector>
2#include <string>
3#include <unordered_map>
4#include <set>
5#include <utility>
6
7using namespace std;
8
9class FoodRatings {
10private:
11 unordered_map<string, pair<int, string>> foodInfo;
12 unordered_map<string, set<pair<int, string>>> cuisineData;
13
14public:
15 FoodRatings(vector<string>& foods, vector<string>& cuisines, vector<int>& ratings) {
16 int n = foods.size();
17 for (int i = 0; i < n; ++i) {
18 foodInfo[foods[i]] = {-ratings[i], cuisines[i]};
19 cuisineData[cuisines[i]].insert({-ratings[i], foods[i]});
20 }
21 }
22
23 void changeRating(string food, int newRating) {
24 auto &[oldRating, cuisine] = foodInfo[food];
25 cuisineData[cuisine].erase({oldRating, food});
26 oldRating = -newRating;
27 cuisineData[cuisine].insert({oldRating, food});
28 }
29
30 string highestRated(string cuisine) {
31 return cuisineData[cuisine].begin()->second;
32 }
33};
C++ implementation uses unordered_map for quick access to food and cuisine data. A set of pairs (negative rating, food name) is used to automatically maintain order in decreasing ratings. When a rating is changed, the old rating is removed before inserting the new pair. The highest-rated food is directly accessed using the beginning iterator of the cuisine-based set.
This approach uses priority queues (heaps) to manage the highest-rated food for a cuisine. Heaps offer efficient operations for maintaining and retrieving maximum values, which can be useful for finding the highest-rated item.
Time Complexity: O(N) for initialization and O(log F) for updating heap or retrieving the maximum where F is the number of foods for given cuisine.
Space Complexity: O(N) for storing the heap elements.
1import heapq
2
3class FoodRatings:
The Python version uses a heap to maintain the highest-rated food for each cuisine. Negative ratings are stored to utilize the min-heap structure for max-heap behavior. If ratings change, old entries may remain invalid due to imposition of new valid values. Therefore, we remove these as necessary during the highestRated check.