#3408
Medium Algorithms Design task manager
Hash Table Design Heap (Priority Queue) Ordered Set
49.1% acceptance
Feb 24, 2026
485
52
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>& 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.
Solution
Rust
Time O(n log n)
Space O(n)
* impl TaskManager {
* fn new(tasks: Vec<Vec<i32>>) -> Self {
* }
* fn add(&self, user_id: i32, task_id: i32, priority: i32) {
* }
* fn edit(&self, task_id: i32, new_priority: i32) {
* }
* fn rmv(&self, task_id: i32) {
* }
* fn exec_top(&self) -> i32 {
* }
* }
*/
use std::collections::{BTreeMap, HashMap};
pub struct TaskManager {
task_info: HashMap<i32, (i32, i32)>,
sorted: BTreeMap<(i32, i32), i32>,
}
impl TaskManager {
pub fn new(tasks: Vec<Vec<i32>>) -> Self {
let mut tm = TaskManager {
task_info: HashMap::new(),
sorted: BTreeMap::new(),
};
for t in tasks {
tm.add(t[0], t[1], t[2]);
}
tm
}
pub fn add(&mut self, user_id: i32, task_id: i32, priority: i32) {
self.task_info.insert(task_id, (user_id, priority));
self.sorted.insert((priority, task_id), user_id);
}
pub fn edit(&mut self, task_id: i32, new_priority: i32) {
if let Some(&(user_id, old_priority)) = self.task_info.get(&task_id) {
self.sorted.remove(&(old_priority, task_id));
self.task_info.insert(task_id, (user_id, new_priority));
self.sorted.insert((new_priority, task_id), user_id);
}
}
pub fn rmv(&mut self, task_id: i32) {
if let Some((_, priority)) = self.task_info.remove(&task_id) {
self.sorted.remove(&(priority, task_id));
}
}
pub fn exec_top(&mut self) -> i32 {
if let Some((&(priority, task_id), &user_id)) = self.sorted.iter().next_back() {
self.sorted.remove(&(priority, task_id));
self.task_info.remove(&task_id);
user_id
} else {
-1
}
}
}