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 java.util.*;
2
3
Java's implementation uses a PriorityQueue as a max-heap storing pairs of ratings and food names. The priority queue sorts lexicographically for tie-breaking. Updates add new valid ratings to the heap and invalid entries are removed lazily during the highestRated request.