Problem
There is a task management system that allows users to manage their tasks, each associated with a priority. The system should efficiently handle adding, modifying, executing, and removing tasks.
Implement the TaskManager
class:
-
TaskManager(vector<vector<int>>& tasks)
initializes the task manager with a list of user-task-priority triples. Each element in the input list is of the form[userId, taskId, priority]
, which adds a task to the specified user with the given priority. -
void add(int userId, int taskId, int priority)
adds a task with the specifiedtaskId
andpriority
to the user withuserId
. It is guaranteed thattaskId
does not exist in the system. -
void edit(int taskId, int newPriority)
updates the priority of the existingtaskId
tonewPriority
. It is guaranteed thattaskId
exists in the system. -
void rmv(int taskId)
removes the task identified bytaskId
from the system. It is guaranteed thattaskId
exists in the system. -
int execTop()
executes the task with the highest priority across all users. If there are multiple tasks with the same highest priority, execute the one with the highesttaskId
. After executing, the****taskId
**** is removed from the system. Return theuserId
associated with the executed task. If no tasks are available, return -1.
Note that a user may be assigned multiple tasks.
Example 1
|
|
Constraints
1 <= tasks.length <= 10^5
0 <= userId <= 10^5
0 <= taskId <= 10^5
0 <= priority <= 10^9
0 <= newPriority <= 10^9
- At most
2 * 10^5
calls will be made in total toadd
,edit
,rmv
, andexecTop
methods. - The input is generated such that
taskId
will be valid.
Examples
Solution
Method 1 – Hash Maps and Max Heap (Priority Queue)
Intuition
We need to efficiently support adding, editing, removing, and executing the highest-priority task. By using a hash map for fast task lookup and a max heap (priority queue) for quick access to the top task, we can achieve all operations efficiently. We use lazy deletion in the heap to handle removals and edits.
Approach
- Use a hash map
taskMap
to storetaskId -> (userId, priority)
. - Use a max heap (priority queue) to store tuples
(-priority, -taskId, taskId)
for quick access to the highest-priority, highest-taskId task. - For
add
, insert into both the map and the heap. - For
edit
, update the map and push the new priority to the heap (old heap entries are ignored via lazy deletion). - For
rmv
, remove from the map (heap entries are ignored via lazy deletion). - For
execTop
, pop from the heap until a valid task is found (exists in the map and priority matches), then remove it from the map and return the userId. If no valid task, return -1.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(log n)
per operation due to heap operations and hash map lookups. - 🧺 Space complexity:
O(n)
, wheren
is the number of tasks in the system.