#3885
Design Event Manager
MediumArrayHash TableDesignHeap (Priority Queue)Ordered SetHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(log n)Space O(n)
Use a priority queue to efficiently manage events by priority, and a hash map to track current priorities.
⚙️
Algorithm
3 steps- 1Step 1: Store events in a priority queue sorted by priority and eventId.
- 2Step 2: Use a hash map to keep track of the current priority of each eventId.
- 3Step 3: In pollHighest, pop from the queue until the top matches the priority in the hash map.
solution.py16 lines
1import heapq
2class EventManager:
3 def __init__(self, events):
4 self.event_map = {event[0]: event[1] for event in events}
5 self.pq = [(event[1], event[0]) for event in events]
6 heapq.heapify(self.pq)
7 def updatePriority(self, eventId, newPriority):
8 self.event_map[eventId] = newPriority
9 heapq.heappush(self.pq, (newPriority, eventId))
10 def pollHighest(self):
11 while self.pq:
12 priority, eventId = heapq.heappop(self.pq)
13 if self.event_map[eventId] == priority:
14 del self.event_map[eventId]
15 return eventId
16 return -1ℹ
Complexity note: Priority queue operations are logarithmic, and we maintain a hash map for constant time access.
- 1Use a priority queue for efficient retrieval of the highest priority event.
- 2Maintain a hash map to track current priorities for quick updates.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.