Prioritized Delayed Job Queue Simulator
Data Structure DesignAuto-graded · 21 test casesLast updated
Simulate a delayed job queue by replaying a log of schedule, reschedule, cancel and poll operations, returning each result in order while respecting priority and time ordering.
Delayed Job Queue Replay
A job queue holds jobs that become runnable at a given time and carry a priority. You are given a log of operations to apply, in order, to an initially empty queue. Return the result of every operation.
Inputs
operations: a list of strings. Each is one of"schedule","reschedule","cancel", or"poll".arguments: a list of the same length.arguments[i]holds the arguments foroperations[i]:"schedule":[job_id, priority, run_at]"reschedule":[job_id, new_run_at]"cancel":[job_id]"poll":[now, limit]
Here job_id is a string, and priority, run_at, new_run_at, now and limit are integers.
Operation rules
A job is pending if it was scheduled and has neither been cancelled nor run. A job is executed once a poll has returned it.
-
schedule: If
job_idis pending or already executed, returnFalseand change nothing. Otherwise add it as pending with the given priority and run time, and returnTrue. A job ID that was cancelled earlier may be scheduled again. -
reschedule: If
job_idis pending, set its run time tonew_run_at, keep its original priority, and returnTrue. Otherwise (unknown, cancelled or executed) returnFalse. -
cancel: If
job_idis pending, remove it and returnTrue. Otherwise returnFalse. -
poll: Consider the pending jobs whose
run_at <= now. Order them by:- higher
priorityfirst, - then smaller
run_atfirst, - then lexicographically smaller
job_idfirst.
Take the first
limitjobs in this order (iflimitis zero or negative, take none). Mark them as executed, so they can no longer be cancelled, rescheduled, scheduled again or polled again. Return their IDs as a list in the order taken. If none qualify, return[]. - higher
The value of now is not guaranteed to increase between polls. Each poll must be judged only on the current pending jobs and its own now.
Output
Return a list with one entry per operation, in the same order: a boolean for schedule, reschedule and cancel, and a list of strings for poll.
Constraints
len(operations) == len(arguments), up to10^5.- Job IDs are strings compared lexicographically.
- Priorities and times are integers.
- Every operation name is one of the four listed above.
Examples
Example 1
Input: replay_job_queue(['schedule', 'schedule', 'schedule', 'schedule', 'reschedule', 'cancel', 'poll', 'poll', 'cancel'], [['taskA', 1, 100], ['taskB', 2, 120], ['taskC', 2, 90], ['taskA', 5, 50], ['taskA', 80], ['taskC'], [100, 5], [150, 1], ['taskB']])
Output: [True, True, True, False, True, True, ['taskA'], ['taskB'], False]
Hints
Hint 1
Keep a map of pending jobs and a set of executed job IDs. Most of the return values for schedule, reschedule and cancel come directly from those two structures.
Hint 2
A poll needs two orderings: which jobs are due (by run time) and which due jobs go first (by priority, run time, ID). A simple correct start is to filter the due jobs and sort them with that key.
Hint 3
To scale to 10^5 operations, use heaps with lazy deletion. Tag each heap entry with a version number and discard entries whose version no longer matches the pending map. Because time may go backwards between polls, a due-heap entry that is not due for the current poll must be returned to the time-ordered heap.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two different orderings are involved:
- Eligibility depends only on
run_at <= now, a time ordering. - Selection order among eligible jobs is
(-priority, run_at, job_id).
One heap cannot serve both, so the solution uses a dictionary plus two heaps.
pendingmapsjob_idto(priority, run_at, version)and is the source of truth for pending jobs.executedis a set of job IDs that have been returned by a poll.time_heapholds(run_at, version, job_id)for jobs not yet moved to the ready heap.ready_heapholds(-priority, run_at, job_id, version)for jobs that were due at some earlier moment.
Cancel and reschedule never search the heaps. They only update pending. Every heap entry carries a version, and an entry is valid only if the job is still pending with that same version. Stale entries are discarded lazily when they reach the top of a heap.
For a poll with (now, limit):
- If
limit <= 0, return[]. - Pop every
time_heapentry withrun_at <= now. Valid ones move toready_heap. - Pop from
ready_heapuntillimitjobs are collected. Skip stale entries. If a valid entry is not due for thisnow(possible when time goes backwards), return it totime_heap. Otherwise mark the job executed and append it to the output.
schedule returns False for IDs that are pending or executed, while cancelled IDs may be scheduled again. reschedule and cancel succeed only for pending jobs.
Why it is correct
Every pending job has exactly one valid heap entry, located in either heap. Scheduling and rescheduling create a fresh version, which invalidates older entries. Cancelling or executing removes the job from pending, which invalidates all of its entries. After step 2, every valid due job is in ready_heap, and ready_heap pops in exactly the required order. Stale and not-due entries are never returned, so the jobs taken are the top limit of the due set.
Complexity
With n operations, each schedule or reschedule adds one heap entry, so heaps hold O(n) entries.
scheduleandreschedule: O(log n).cancel: O(1).poll: O((k + s) log n), wherekis the number returned andsis the number of stale or moved entries handled. With non-decreasingnow, each entry moves at most once, giving O(n log n) overall.
Space is O(n).
A simpler approach filters and sorts all pending jobs on every poll. It is correct but can become quadratic.
Reference solution
import heapq
from typing import List
def replay_job_queue(operations: List[str], arguments: List[List]) -> List:
pending = {} # job_id -> (priority, run_at, version)
executed = set()
time_heap = [] # (run_at, version, job_id)
ready_heap = [] # (-priority, run_at, job_id, version)
version = 0
results = []
def valid(job_id, ver):
info = pending.get(job_id)
return info is not None and info[2] == ver
for operation, args in zip(operations, arguments):
if operation == "schedule":
job_id, priority, run_at = args
if job_id in pending or job_id in executed:
results.append(False)
else:
version += 1
pending[job_id] = (priority, run_at, version)
heapq.heappush(time_heap, (run_at, version, job_id))
results.append(True)
elif operation == "reschedule":
job_id, new_run_at = args
if job_id not in pending:
results.append(False)
else:
version += 1
priority = pending[job_id][0]
pending[job_id] = (priority, new_run_at, version)
heapq.heappush(time_heap, (new_run_at, version, job_id))
results.append(True)
elif operation == "cancel":
job_id = args[0]
if job_id in pending:
del pending[job_id]
results.append(True)
else:
results.append(False)
elif operation == "poll":
now, limit = args
out = []
if limit > 0:
while time_heap and time_heap[0][0] <= now:
run_at, ver, job_id = heapq.heappop(time_heap)
if valid(job_id, ver):
priority = pending[job_id][0]
heapq.heappush(ready_heap, (-priority, run_at, job_id, ver))
while ready_heap and len(out) < limit:
neg_p, run_at, job_id, ver = heapq.heappop(ready_heap)
if not valid(job_id, ver):
continue
if run_at > now:
heapq.heappush(time_heap, (run_at, ver, job_id))
continue
del pending[job_id]
executed.add(job_id)
out.append(job_id)
results.append(out)
else:
raise ValueError("Unknown operation: " + str(operation))
return results