Priority Job Scheduler with Cancellation
Data Structure DesignAuto-graded · 23 test casesLast updated
Simulate a scheduler that adds, cancels, and runs jobs by priority with FIFO tie-breaking, using lazy deletion on a heap so each operation stays logarithmic.
Priority Job Scheduler with Cancellation
You are simulating a job scheduler that holds a set of pending jobs. Each job has a unique integer id and an integer priority. The scheduler processes a sequence of commands and reports a result for each one.
Commands
The input consists of two parallel lists. commands[i] is the name of the i-th command and params[i] is the list of integer parameters for it.
| Command | Parameters | Effect | Result |
|---|---|---|---|
"add" | [job_id, priority] | Registers a pending job with this id and priority. If a job with the same id is already pending, it is replaced by the new one (new priority, and it counts as newly arrived for tie-breaking). | None |
"remove" | [job_id] | Cancels the pending job with this id. If there is no such pending job (never added, already cancelled, or already run), nothing happens. | None |
"executeNext" | [] | Picks the best pending job, removes it from the scheduler, and returns its id. If nothing is pending, returns None. | job id or None |
Any command name other than "add" and "remove" should be treated as "executeNext".
Ordering rule
The best pending job is the one with the highest priority. If several pending jobs share the highest priority, the one that was added earliest is chosen. Arrival order is determined by the order of add commands: every add counts as a new arrival, including one that replaces an existing pending job with the same id or re-adds an id that was previously cancelled or run.
Task
Implement a function that processes all commands in order and returns a list with one result per command, in the same order.
Your solution should not scan all pending jobs when executing the next one; aim for O(log n) time per command (amortized is acceptable).
Constraints
len(commands) == len(params)- Job ids and priorities are integers; priorities may be zero or negative.
- Cancelling or executing a job that is not pending is not an error.
executeNexton an empty scheduler returnsNone.- A job id can be added, cancelled, and added again any number of times.
Examples
Example 1
Input: run_scheduler(['add', 'add', 'executeNext', 'executeNext'], [[1, 5], [2, 5], [], []])
Output: [None, None, 1, 2]
Example 2
Input: run_scheduler(['add', 'add', 'remove', 'executeNext', 'executeNext'], [[10, 3], [11, 8], [11], [], []])
Output: [None, None, None, 10, None]
Example 3
Input: run_scheduler(['executeNext', 'remove', 'add', 'remove', 'executeNext'], [[], [99], [7, 1], [7], []])
Output: [None, None, None, None, None]
Hints
Hint 1
A binary heap gives fast access to the best job, but it cannot remove an arbitrary buried element cheaply. Think about deferring the removal.
Hint 2
Store entries as (-priority, arrival_counter, job_id) so that Python's min-heap yields the highest priority first and the earliest arrival wins ties. Keep a dictionary of the currently valid entry for each job id.
Hint 3
On cancel, just delete the id from the dictionary. When executing, pop heap entries until one equals the dictionary's current entry for its id; compare the whole entry, not just whether the id exists, so re-added ids do not resurrect old entries.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A heap gives quick access to the best job, but removing an arbitrary element from the middle of a heap is expensive. So we use lazy deletion.
- Keep a min-heap of entries
(-priority, counter, job_id). Negating the priority makes the highest priority pop first. The counter increases with everyadd, so among equal priorities the earlier arrival pops first. - Keep a dictionary
currentmapping each pending job id to its one valid heap entry. add: build a new entry with a fresh counter, store it incurrent, and push it onto the heap. Any older entry for the same id is now outdated because it no longer equalscurrent[job_id].remove: just delete the id fromcurrent(no-op if absent). The heap entry stays behind as a stale record.executeNext: pop entries from the heap until one equalscurrent[job_id]. Stale entries are discarded. The valid one is removed fromcurrentand its id is returned. If the heap empties first, returnNone.
Why it is correct
Invariant: every pending job has exactly one heap entry equal to its current entry; every other heap entry is stale. The heap minimum is the smallest (-priority, counter) over all entries, so discarding a stale minimum loses nothing, and the first valid entry found is the smallest among valid ones, which is the highest priority with the earliest arrival. Because counters are unique, every entry is unique, so comparing whole entries correctly identifies stale ones, including after remove-then-re-add or replacing an active id.
Complexity
Let m be the number of add commands.
add: O(log m).remove: O(1).executeNext: amortized O(log m), since each entry is popped at most once over the whole run.- Space: O(m), since stale entries remain until they surface.
Reference solution
import heapq
from typing import List, Optional
def run_scheduler(commands: List[str], params: List[List[int]]) -> List[Optional[int]]:
heap = []
current = {}
counter = 0
results = []
for command, args in zip(commands, params):
if command == "add":
job_id, priority = args
entry = (-priority, counter, job_id)
counter += 1
current[job_id] = entry
heapq.heappush(heap, entry)
results.append(None)
elif command == "remove":
current.pop(args[0], None)
results.append(None)
else:
answer = None
while heap:
entry = heapq.heappop(heap)
job_id = entry[2]
if current.get(job_id) == entry:
del current[job_id]
answer = job_id
break
results.append(answer)
return results