Latest-Wins Priority Job Runner Simulation
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a job runner where resubmitting an ID overrides its earlier entry, testing heap-based lazy deletion with tie-breaking and run-once rules.
Latest-Wins Priority Job Runner
You are simulating a job runner that holds pending jobs and runs them one at a time. Each job has an integer id, an integer priority, and an integer timestamp. You receive a sequence of commands and must report what each run command returns.
Commands
The two input lists have the same length. commands[i] is the name of the i-th command, and params[i] holds its arguments.
"addTask"withparams[i] = [task_id, priority, timestamp]submits a job.- If
task_idhas never been submitted, it becomes pending with the given priority and timestamp. - If
task_idis already pending, the new priority and timestamp replace the old ones. The most recent submission wins, even if its priority is lower than before. - If
task_idhas already been run, the submission is ignored completely.
- If
"executeTask"withparams[i] = []picks the next pending job, removes it, and returns its id. After this, the id counts as run and can never run again.
Choosing the next job
Among the pending jobs, choose the one that has:
- the highest priority;
- if priorities tie, the smallest timestamp;
- if both tie, the smallest task id.
Only each job's current (latest) priority and timestamp are considered.
If no job is pending, executeTask returns None (null in the sample outputs).
Output
Return a list with one entry per "executeTask" command, in order. Each entry is the returned id or None. "addTask" commands add nothing to the output.
Constraints
1 <= len(commands) <= 10^5, andlen(params) == len(commands).- Every command is either
"addTask"or"executeTask". - Task ids, priorities and timestamps are integers and may be negative.
- The same id may be submitted many times.
- The solution should run in about O(n log n) overall.
Examples
Example 1
Input: simulate_priority_runner(['addTask', 'addTask', 'addTask', 'executeTask', 'executeTask'], [[1, 10, 100], [2, 20, 50], [1, 15, 120], [], []])
Output: [2, 1]
Example 2
Input: simulate_priority_runner(['addTask', 'addTask', 'executeTask', 'addTask', 'executeTask', 'executeTask'], [[7, 5, 10], [3, 5, 10], [], [7, 100, 1], [], []])
Output: [3, 7, None]
Hints
Hint 1
Python's heapq is a min-heap. How can you encode 'highest priority first, then earliest timestamp, then smallest id' as a tuple that sorts ascending?
Hint 2
A heap cannot cheaply update or remove an arbitrary entry. Instead of editing the old entry, push a new one and remember which entry is currently valid for each id.
Hint 3
Give each submission a version number per id. When you pop, discard entries whose version is not the latest one stored for that id, and keep a set of ids that already ran so later submissions are ignored.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A heap gives fast access to the best job, but it cannot update or delete an arbitrary entry. So we use lazy deletion:
- Every
addTaskpushes a new heap entry(-priority, timestamp, task_id, version). Negating the priority makes the min-heap return the highest priority first, then the earliest timestamp, then the smallest id. latestmaps each pending id to the version of its live entry. Resubmitting an id bumps its version and overwrites this value, which makes all of its older heap entries outdated.doneholds the ids that have run. AnaddTaskfor such an id is skipped immediately.executeTaskpops entries until it finds one whose version matcheslatest[task_id]. Outdated entries are discarded. The matching id is removed fromlatest, added todone, and returned. If the heap empties first, the result isNone.
Why it is correct
- Each pending id has exactly one live entry, the one from its most recent submission. All earlier entries fail the version check and are never returned.
- Outdated entries may sit above live ones, but skipping them does not change the relative order of live entries. So the first live entry popped is the best pending job under the (priority, timestamp, id) rule.
- Once an id runs, it is removed from
latest, so its leftover heap entries fail the check. It is also added todone, so no later submission can revive it. - The version number keeps validity unambiguous even if two submissions of the same id have identical priority and timestamp.
Complexity
With n commands:
- Time: O(n log n) overall. Each pushed entry is popped at most once, and each push or pop costs O(log n). A single
executeTaskmay be slow, but the amortized cost is O(log n). - Space: O(n) for the heap, which keeps every submission until it is popped.
Reference solution
import heapq
from typing import List, Optional
def simulate_priority_runner(commands: List[str], params: List[List[int]]) -> List[Optional[int]]:
heap = [] # (-priority, timestamp, task_id, version)
latest = {} # task_id -> version of the live heap entry (pending ids only)
counter = {} # task_id -> number of submissions so far
done = set() # ids that have already run
output = []
for cmd, args in zip(commands, params):
if cmd == "addTask":
task_id, priority, timestamp = args
if task_id in done:
continue
ver = counter.get(task_id, 0) + 1
counter[task_id] = ver
latest[task_id] = ver
heapq.heappush(heap, (-priority, timestamp, task_id, ver))
else:
result = None
while heap:
_, _, task_id, ver = heapq.heappop(heap)
if latest.get(task_id) != ver:
continue # outdated or already executed entry
del latest[task_id]
done.add(task_id)
result = task_id
break
output.append(result)
return output