LeetCode in Kotlin

3408. Design Task Manager

Medium

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:

Note that a user may be assigned multiple tasks.

Example 1:

Input:
[“TaskManager”, “add”, “edit”, “execTop”, “rmv”, “add”, “execTop”]
[[[[1, 101, 10], [2, 102, 20], [3, 103, 15]]], [4, 104, 5], [102, 8], [], [101], [5, 105, 15], []]

Output:
[null, null, null, 3, null, null, 5]

Explanation

TaskManager taskManager = new TaskManager([[1, 101, 10], [2, 102, 20], [3, 103, 15]]); // Initializes with three tasks for Users 1, 2, and 3.
taskManager.add(4, 104, 5); // Adds task 104 with priority 5 for User 4.
taskManager.edit(102, 8); // Updates priority of task 102 to 8.
taskManager.execTop(); // return 3. Executes task 103 for User 3.
taskManager.rmv(101); // Removes task 101 from the system.
taskManager.add(5, 105, 15); // Adds task 105 with priority 15 for User 5.
taskManager.execTop(); // return 5. Executes task 105 for User 5.

Constraints:

Solution

import java.util.TreeSet

class TaskManager(tasks: List<List<Int>>) {
    private val tasks: TreeSet<IntArray?>
    private val taskMap: MutableMap<Int?, IntArray>

    init {
        this.tasks =
            TreeSet<IntArray?>(
                Comparator { a: IntArray?, b: IntArray? ->
                    if (b!![2] == a!![2]) b[1] - a[1] else b[2] - a[2]
                },
            )
        this.taskMap = HashMap<Int?, IntArray>()
        for (task in tasks) {
            val t = intArrayOf(task[0], task[1], task[2])
            this.tasks.add(t)
            this.taskMap.put(task[1], t)
        }
    }

    fun add(userId: Int, taskId: Int, priority: Int) {
        val task = intArrayOf(userId, taskId, priority)
        this.tasks.add(task)
        this.taskMap.put(taskId, task)
    }

    fun edit(taskId: Int, newPriority: Int) {
        val task: IntArray = taskMap[taskId]!!
        tasks.remove(task)
        taskMap.remove(taskId)
        val newTask = intArrayOf(task[0], task[1], newPriority)
        tasks.add(newTask)
        taskMap.put(taskId, newTask)
    }

    fun rmv(taskId: Int) {
        this.tasks.remove(this.taskMap[taskId])
        this.taskMap.remove(taskId)
    }

    fun execTop(): Int {
        if (this.tasks.isEmpty()) {
            return -1
        }
        val task = this.tasks.pollFirst()
        this.taskMap.remove(task!![1])
        return task[0]
    }
}

/*
 * 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();
 */