- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 93 lines of C++ from the credited upstream file design-event-manager.cpp.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 4 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12345 67class EventManager {8public:9 EventManager(vector<vector<int>>& events) {10 vector<pair<int, int>> pairs;11 for (const auto& e : events) {12 lookup_[e[0]] = e[1];13 pairs.emplace_back(e[1], -e[0]);14 }15 priority_queue<pair<int, int>> tmp(cbegin(pairs), cend(pairs));16 max_heap_.swap(tmp);17 }18 19 void updatePriority(int eventId, int newPriority) {20 lookup_[eventId] = newPriority;21 max_heap_.emplace(newPriority, -eventId);22 if (size(max_heap_) > 2 * size(lookup_)) {23 rebuild();24 }25 }26 27 int pollHighest() {28 for (; !empty(max_heap_); max_heap_.pop()) {29 const auto [p, i] = max_heap_.top();30 if (lookup_.count(-i) && lookup_[-i] == p) {31 lookup_.erase(-i);32 return -i;33 }34 }35 return -1;36 }37 38private:39 void rebuild() {40 unordered_map<int, int> lookup;41 priority_queue<pair<int, int>> max_heap;42 for (; !empty(max_heap_); max_heap_.pop()) {43 const auto [p, i] = max_heap_.top();44 if (lookup_.count(-i) && lookup_[-i] == p) {45 lookup_.erase(-i);46 lookup[-i] = p;47 max_heap.emplace(p, i);48 }49 }50 lookup_.swap(lookup);51 max_heap_.swap(max_heap);52 }53 54 unordered_map<int, int> lookup_;55 priority_queue<pair<int, int>> max_heap_;56};57 585960616263class EventManager2 {64public:65 EventManager2(vector<vector<int>>& events) {66 for (const auto& e : events) {67 lookup_[e[0]] = e[1];68 bst_.emplace(e[1], -e[0]);69 }70 }71 72 void updatePriority(int eventId, int newPriority) {73 bst_.erase(pair(lookup_[eventId], -eventId));74 lookup_[eventId] = newPriority;75 bst_.emplace(newPriority, -eventId);76 }77 78 int pollHighest() {79 if (empty(bst_)) {80 return -1;81 }82 auto it = prev(cend(bst_));83 const int result = -it->second;84 bst_.erase(it);85 lookup_.erase(result);86 return result;87 }88 89private:90 unordered_map<int, int> lookup_;91 set<pair<int, int>> bst_;92};93