- 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
- 96 lines of Python from the credited upstream file design-event-manager.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit 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 6import heapq7 8 910class EventManager(object):11 12 def __init__(self, events):13 """14 :type events: List[List[int]]15 """16 self.__lookup = {}17 self.__max_heap = []18 for i, p in events:19 self.__lookup[i] = p20 self.__max_heap.append((-p, i))21 heapq.heapify(self.__max_heap)22 23 def updatePriority(self, eventId, newPriority):24 """25 :type eventId: int26 :type newPriority: int27 :rtype: None28 """29 self.__lookup[eventId] = newPriority30 heapq.heappush(self.__max_heap, (-newPriority, eventId))31 if len(self.__max_heap) > 2*len(self.__lookup):32 self.__rebuild()33 34 def pollHighest(self):35 """36 :rtype: int37 """38 while self.__max_heap:39 p, i = heapq.heappop(self.__max_heap)40 if i in self.__lookup and self.__lookup[i] == -p:41 del self.__lookup[i]42 return i43 return -144 45 def __rebuild(self):46 lookup = {}47 max_heap = []48 while self.__max_heap:49 p, i = heapq.heappop(self.__max_heap)50 if i in self.__lookup and self.__lookup[i] == -p:51 del self.__lookup[i]52 lookup[i] = -p53 heapq.heappush(max_heap, (p, i))54 self.__lookup, self.__max_heap = lookup, max_heap55 56 5758596061from sortedcontainers import SortedList62 63 6465class EventManager2(object):66 67 def __init__(self, events):68 """69 :type events: List[List[int]]70 """71 self.__lookup = {}72 self.__sl = SortedList()73 for i, p in events:74 self.__lookup[i] = p75 self.__sl.add((p, -i))76 77 def updatePriority(self, eventId, newPriority):78 """79 :type eventId: int80 :type newPriority: int81 :rtype: None82 """83 self.__sl.remove((self.__lookup[eventId], -eventId))84 self.__lookup[eventId] = newPriority85 self.__sl.add((newPriority, -eventId)) 86 87 def pollHighest(self):88 """89 :rtype: int90 """91 if not self.__sl:92 return -193 result = -self.__sl.pop()[1]94 self.__lookup.pop(result)95 return result96