[LeetCode] Design Task Manager

3408. Design Task Manager

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 specified taskId and priority to the user with userId. It is guaranteed that taskId does not exist in the system.
  • void edit(int taskId, int newPriority) updates the priority of the existing taskId to newPriority. It is guaranteed that taskId exists in the system.
  • void rmv(int taskId) removes the task identified by taskId from the system. It is guaranteed that taskId 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 highest taskId. After executing, the taskId is removed from the system. Return the userId associated with the executed task. If no tasks are available, return -1.

Note that a user may be assigned multiple tasks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

class TaskManager {
map<int,set<int>> ptasks;
unordered_map<int, pair<int,int>> tasks;
public:
TaskManager(vector<vector<int>>& T) {
ptasks = {}, tasks = {};
for(auto& task : T) {
int u = task[0], t = task[1], p = task[2];
add(u,t,p);
}
}

void add(int userId, int taskId, int priority) {
ptasks[priority].insert(taskId);
tasks[taskId] = {userId, priority};
}

void edit(int taskId, int newPriority) {
ptasks[tasks[taskId].second].erase(taskId);
if(ptasks[tasks[taskId].second].size() == 0) {
ptasks.erase(tasks[taskId].second);
}
tasks[taskId].second = newPriority;
ptasks[newPriority].insert(taskId);
}

void rmv(int taskId) {
ptasks[tasks[taskId].second].erase(taskId);
if(ptasks[tasks[taskId].second].size() == 0) {
ptasks.erase(tasks[taskId].second);
}
tasks.erase(taskId);
}

int execTop() {
if(ptasks.empty()) return -1;
int task = *prev(end(prev(end(ptasks))->second));
int userId = tasks[task].first;
rmv(task);
return userId;
}
};

/**
* Your TaskManager object will be instantiated and called as such:
* TaskManager* obj = new TaskManager(tasks);
* obj->add(userId,taskId,priority);
* obj->edit(taskId,newPriority);
* obj->rmv(taskId);
* int param_4 = obj->execTop();
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/01/05/PS/LeetCode/design-task-manager/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.