Task Scheduler With Removal
Implement a scheduler that holds tasks until they are popped in timestamp order.
addTask(taskId, timestamp)schedules a task. IftaskIdis already scheduled, the call replaces its timestamp.removeTask(taskId)cancels a scheduled task. Returntrueif it was scheduled andfalseotherwise.popTask(num)removes and returns the ids of the firstnumtasks, earliest timestamp first. Tasks with equal timestamps come out in the order they were added (a replaced task counts as added at the moment of replacement). When fewer thannumtasks remain, return all of them.
addTask("build", 30) addTask("lint", 10) addTask("test", 20)
removeTask("test") -> true
popTask(2) -> ["lint", "build"]
popTask(1) -> []addTask and removeTask should not scan the scheduled tasks; aim for O(log n) per added or popped task.
Hints
Hint 1
Ordered retrieval wants a min-heap keyed by (timestamp, sequence); removal by id wants a hash map. The work is making them agree.
Hint 2
Do not search the heap on removal. Delete the id from the map and leave the heap entry behind; when it reaches the top, recognise it as stale and skip it.
Hint 3
A replaced timestamp leaves an old entry in the heap for the same id, so presence in the map is not enough. Store the sequence number of the live entry and compare.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.