Route Jobs to Workers with Account Stickiness
Heaps, Sorting & SearchAuto-graded · 19 test casesLast updated
Simulate FIFO dispatch of tasks to workers with a preference for each account's last worker, using heaps and a lookup table to track free and busy workers.
Sticky Task Router
A processing platform has a fixed pool of workers and a queue of tasks. Every task is already in the queue at time 0, and tasks are dispatched strictly in the order given. Your job is to decide which worker handles each task and when it finishes.
Input
tasks: a list of dicts, each with integer keystask_id,account_idandprocessing_time.workers: a list of dicts, each with an integerworker_idand a stringtype. Worker IDs are unique but not necessarily consecutive. Thetypefield (for example"General"or"Specialized") is informational only and has no effect on the result.
Dispatch model
Keep a single dispatch clock that starts at 0. Each worker handles one task at a time. A worker that starts a task at clock value c with processing time p is busy until c + p. A worker is idle at clock value c if it has never been used, or if its busy-until time is less than or equal to c.
Handle the tasks one by one, in input order:
-
If no worker is idle at the current clock, advance the clock to the smallest busy-until time among all workers. Every worker whose busy-until time is at most the new clock value is now idle. The clock changes only in this situation. It never moves forward otherwise, so several consecutive tasks can start at the same clock value.
-
Choose a worker for the task:
- Stickiness: if the task's
account_idhas been handled before, and the worker who handled that account most recently is idle right now, choose that worker. - Otherwise choose the idle worker with the smallest
worker_id.
Stickiness is only a preference. Never delay a task to wait for a busy preferred worker.
- Stickiness: if the task's
-
The task starts at the current clock value, so its
finish_timeisclock + processing_time. The chosen worker is busy until that time. Record this worker as the latest handler of the task's account.
Output
Return a list with one dict per task, in the same order as the input tasks. Each dict has the keys task_id, worker_id (the chosen worker) and finish_time.
Constraints
1 <= len(tasks) <= 10^51 <= len(workers) <= 1000- Every
processing_timeis a positive integer. - Worker IDs are distinct.
- Tasks must be dispatched in the given order, and the output order matches the input order.
Examples
Example 1
Input: route_tasks([{'task_id': 1, 'account_id': 100, 'processing_time': 5}, {'task_id': 2, 'account_id': 100, 'processing_time': 3}], [{'worker_id': 1, 'type': 'General'}, {'worker_id': 2, 'type': 'General'}])
Output: [{'task_id': 1, 'worker_id': 1, 'finish_time': 5}, {'task_id': 2, 'worker_id': 2, 'finish_time': 3}]
Example 2
Input: route_tasks([{'task_id': 1, 'account_id': 10, 'processing_time': 4}, {'task_id': 2, 'account_id': 20, 'processing_time': 2}, {'task_id': 3, 'account_id': 30, 'processing_time': 3}], [{'worker_id': 1, 'type': 'General'}, {'worker_id': 2, 'type': 'Specialized'}])
Output: [{'task_id': 1, 'worker_id': 1, 'finish_time': 4}, {'task_id': 2, 'worker_id': 2, 'finish_time': 2}, {'task_id': 3, 'worker_id': 2, 'finish_time': 5}]
Example 3
Input: route_tasks([{'task_id': 1, 'account_id': 1, 'processing_time': 5}, {'task_id': 2, 'account_id': 1, 'processing_time': 2}, {'task_id': 3, 'account_id': 2, 'processing_time': 1}, {'task_id': 4, 'account_id': 2, 'processing_time': 4}], [{'worker_id': 3, 'type': 'General'}, {'worker_id': 7, 'type': 'General'}])
Output: [{'task_id': 1, 'worker_id': 3, 'finish_time': 5}, {'task_id': 2, 'worker_id': 7, 'finish_time': 2}, {'task_id': 3, 'worker_id': 7, 'finish_time': 3}, {'task_id': 4, 'worker_id': 7, 'finish_time': 7}]
Hints
Hint 1
The clock only jumps when every worker is busy, and it jumps to the earliest busy-until time. What structure gives you that earliest time quickly?
Hint 2
Keep two heaps: one of idle worker IDs (to get the smallest ID) and one of (busy_until, worker_id) pairs. Before each task, move every worker with busy_until <= clock from the busy heap to the idle structure.
Hint 3
For stickiness, store the last worker per account in a dict and keep an is_idle flag per worker. If you take the preferred worker out of the middle of the idle heap, delete lazily: when popping, skip IDs whose flag says busy.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is an event-driven simulation. The state is the dispatch clock plus, for each worker, whether it is idle. We need four things quickly:
- Smallest idle worker ID. A min-heap
idle_heapof worker IDs. - Earliest completion time. A min-heap
busy_heapof(busy_until, worker_id)pairs. - Is worker X idle? A dict
is_idle, plus a counteridle_count. - Last worker of an account. A dict
last_worker.
For each task, in order:
- Move every worker with
busy_until <= clockfrombusy_heapto the idle structure. - If nobody is idle, set the clock to the smallest
busy_untiland release again. All workers finishing at that instant become idle together. - If the account's previous worker is idle, use it. Otherwise pop the smallest idle ID.
- Set
finish = clock + processing_time, push(finish, worker)ontobusy_heap, and updatelast_worker.
Lazy deletion
When stickiness picks a worker from the middle of idle_heap, we do not remove it from the heap. We only mark it busy. When popping for the smallest ID, we discard entries whose is_idle flag is False. A worker can end up with duplicate heap entries, but a duplicate only counts when the flag says idle, which means the worker really is idle. The total number of pushes is at most W + T, so the heap stays small.
Why it is correct
- The clock never decreases. It jumps only to the minimum
busy_until, and everybusy_untilat or below the old clock was already released. - A task starts at the earliest moment any worker can take it. Tasks are FIFO, so no earlier legal start exists.
- Release uses
<=, so a worker that finishes exactly at the clock value counts as idle. This includes the case where it is the preferred worker. - Selection follows the rules exactly. The preferred worker wins if idle, and otherwise the smallest idle ID wins. The preferred worker is never waited for.
- The account's latest worker is overwritten after every assignment, so stickiness always follows the most recent handler.
Complexity
With T tasks and W workers:
- Time:
O((T + W) log W). Each task causes amortized O(1) heap pushes and pops. - Space:
O(W + A + T), whereAis the number of distinct accounts. The output itself isO(T).
Reference solution
import heapq
from typing import Dict, List
def route_tasks(tasks: List[Dict], workers: List[Dict]) -> List[Dict]:
idle_heap = [w["worker_id"] for w in workers]
heapq.heapify(idle_heap)
is_idle = {w["worker_id"]: True for w in workers}
idle_count = len(workers)
busy_heap = [] # (busy_until, worker_id)
last_worker = {} # account_id -> worker_id
clock = 0
result = []
for task in tasks:
# Release every worker that is done by the current clock.
while busy_heap and busy_heap[0][0] <= clock:
_, wid = heapq.heappop(busy_heap)
is_idle[wid] = True
idle_count += 1
heapq.heappush(idle_heap, wid)
# Everyone busy: jump to the earliest completion time.
if idle_count == 0:
clock = busy_heap[0][0]
while busy_heap and busy_heap[0][0] <= clock:
_, wid = heapq.heappop(busy_heap)
is_idle[wid] = True
idle_count += 1
heapq.heappush(idle_heap, wid)
account = task["account_id"]
preferred = last_worker.get(account)
if preferred is not None and is_idle[preferred]:
chosen = preferred
else:
# Lazy deletion: skip entries for workers that are no longer idle.
while True:
candidate = heapq.heappop(idle_heap)
if is_idle[candidate]:
chosen = candidate
break
is_idle[chosen] = False
idle_count -= 1
finish = clock + task["processing_time"]
heapq.heappush(busy_heap, (finish, chosen))
last_worker[account] = chosen
result.append({
"task_id": task["task_id"],
"worker_id": chosen,
"finish_time": finish,
})
return result