#3408
Design Task Manager
MediumHash 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)
This approach uses a hash map to store tasks by user and a priority queue to efficiently retrieve and execute the highest priority task. This allows for faster operations compared to the brute force method.
⚙️
Algorithm
2 steps- 1Step 1: Use a hash map to store tasks for each user and a max heap to manage task priorities.
- 2Step 2: For add, insert the task into the hash map and heap; for edit, update the priority in the heap; for rmv, remove the task from both structures; for execTop, pop the highest priority task from the heap.
solution.py20 lines
1import heapq
2class TaskManager:
3 def __init__(self, tasks):
4 self.user_tasks = {}
5 self.priority_queue = []
6 for uid, tid, prio in tasks:
7 self.add(uid, tid, prio)
8 def add(self, userId, taskId, priority):
9 self.user_tasks[taskId] = (userId, priority)
10 heapq.heappush(self.priority_queue, (-priority, taskId))
11 def edit(self, taskId, newPriority):
12 self.user_tasks[taskId] = (self.user_tasks[taskId][0], newPriority)
13 heapq.heappush(self.priority_queue, (-newPriority, taskId))
14 def rmv(self, taskId):
15 del self.user_tasks[taskId]
16 def execTop(self):
17 while self.priority_queue:
18 priority, taskId = heapq.heappop(self.priority_queue)
19 if taskId in self.user_tasks:
20 return taskIdℹ
Complexity note: Using a priority queue allows efficient retrieval of the highest priority task, while the hash map provides O(1) access for task management.
- 1Using a priority queue allows efficient task execution.
- 2Hash maps provide quick access and modification of tasks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.