call(back)
Algorithms & Data StructuresmediumSign in to star problems

Task Scheduler With Removal

Implement a scheduler that holds tasks until they are popped in timestamp order.

  • addTask(taskId, timestamp) schedules a task. If taskId is already scheduled, the call replaces its timestamp.
  • removeTask(taskId) cancels a scheduled task. Return true if it was scheduled and false otherwise.
  • popTask(num) removes and returns the ids of the first num tasks, 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 than num tasks 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

Similar Problems6