Skill-Based Task Dispatcher Simulation
Data Structure DesignAuto-graded · 14 test casesLast updated
Simulate a dispatcher that gives queued tasks to skilled workers by project priority and current load, using per-project queues and tie-break rules.
Skill-Based Task Dispatcher
You are building a small dispatcher that hands queued work items to workers. Each worker has a set of skills and a limit on how many items they can hold at once. Each project demands certain skills and has a priority.
Instead of a class, you implement one function that replays a script of commands against a fresh, empty dispatcher and returns one result per command.
Input
commands: a list of command names.payloads: a list of the same length.payloads[i]is the argument list forcommands[i].
Commands
| Command | Payload | Effect | Result recorded |
|---|---|---|---|
"register_annotator" | [worker_id, skills, capacity] | Creates a worker, or updates an existing worker's skills and capacity. A worker that already exists keeps all of its currently active tasks. | None |
"add_project" | [project_id, required_skills, priority] | Creates a project, or updates an existing project's required skills and priority. An existing project keeps its pending tasks and its original creation order. | None |
"add_tasks" | [project_id, task_ids] | Appends the task IDs, in the given order, to the end of that project's pending queue. | None |
"assign_next" | [] | Performs an assignment round (see below). | List of [task_id, project_id, worker_id] triples, in the order the assignments were made. The list is empty if nothing was assigned. |
"complete_task" | [task_id] | Finishes an active task and frees one slot for the worker holding it. | True if the task was active, otherwise False (unknown, still pending, or already completed) |
Assignment round
During "assign_next":
- Consider only projects that currently have at least one pending task.
- Visit those projects from highest
priorityto lowest. Projects with equal priority are visited in the order they were first created. - For the current project, repeatedly take the task at the front of its queue (FIFO) and give it to a worker who is eligible:
- The worker has every skill in the project's
required_skills. An empty requirement list is satisfied by every worker. - The worker's number of active tasks is strictly less than their capacity. A worker whose capacity is 0, or was lowered below their current load, is not eligible.
- The worker has every skill in the project's
- If several workers are eligible, pick the one with the fewest active tasks. If that is still tied, pick the one whose ID is lexicographically smallest.
- Assigning a task immediately raises that worker's active count by one, so later assignments in the same round see the updated load.
- If no worker is eligible for a project, leave its remaining tasks pending and move on to the next project. A blocked project never prevents lower-priority projects from being served. Never discard a task that could not be assigned.
Assigned tasks stay active until "complete_task" is called for them. Task IDs are unique across the whole script. A task is never assigned twice.
Output
Return a list with exactly one entry per command, in order, following the "Result recorded" column above.
Constraints
- Total tasks
<= 10^5. - Workers
<= 500. - Projects
<= 1,000. - Each skill list has at most 20 entries. Skill lists may contain duplicates, and order does not matter.
- All IDs are non-empty alphanumeric strings.
"add_tasks"is only issued for projects that already exist.
Examples
Example 1
Input: simulate_dispatcher(['register_annotator', 'register_annotator', 'add_project', 'add_tasks', 'add_project', 'add_tasks', 'assign_next', 'complete_task', 'complete_task'], [['ann_1', ['nlp', 'audio'], 2], ['ann_2', ['nlp'], 1], ['proj_a', ['nlp'], 5], ['proj_a', ['t1', 't2']], ['proj_b', ['audio'], 10], ['proj_b', ['t3']], [], ['t1'], ['non_existent']])
Output: [None, None, None, None, None, None, [['t3', 'proj_b', 'ann_1'], ['t1', 'proj_a', 'ann_2'], ['t2', 'proj_a', 'ann_1']], True, False]
Hints
Hint 1
Keep pending state (one FIFO queue per project) separate from active state (task to worker, and worker to current load).
Hint 2
Treat skills as sets and test with a subset check. Use a strict 'load < capacity' check so lowered capacities never produce negative free slots.
Hint 3
Inside a project, build a min-heap of eligible workers keyed by (load, id), pop the best, assign, then push the worker back only if they still have room. Rebuild the heap for each project so loads from earlier projects are respected.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The command replay is simple, but the state has to stay consistent across five interacting commands. Keep two kinds of state:
- Pending: one FIFO deque per project, plus the project's skills, priority and creation index.
- Active: a map from task to worker, and each worker's current load.
Updating a worker or project only overwrites its skills, capacity or priority. It never touches load, pending queues or creation order.
Assignment round
- Collect projects that have pending tasks and sort them by
(-priority, creation_order). - For each project, build a min-heap of
(load, worker_id)over workers that are below capacity and whose skill set is a superset of the project's required skills. Tuple ordering gives "fewest active tasks, then smallest ID" automatically. - While the project has tasks and the heap is non-empty, pop the best worker and take the front task. Increase the worker's load, record the assignment, and push the worker back only if they still have free capacity.
- If the heap empties first, the rest of the project's tasks stay queued and the loop moves on to the next project. A task is only removed from the queue once a worker is chosen, so none are lost.
The heap is rebuilt for each project, so it always reflects loads changed by earlier projects in the same round. Within a project, the only load changes come from that project's own assignments, and each is pushed back with its new value, so the heap never holds stale entries.
Completing a task
Look the task up in the active map. If it is missing (unknown, pending or already completed), return False. Otherwise pop it, decrement the worker's load and return True. Popping makes a second completion return False.
Why it is correct
- Projects are visited in
(-priority, creation_order)order, which gives the required priority rule and tie-break. - Tasks leave each project's deque from the left, which preserves FIFO order.
- Each assignment picks the minimum
(load, id)among eligible workers, which is exactly the stated rule. - The strict
load < captest means workers with capacity 0, or capacity lowered below their load, are never chosen, while their existing tasks stay active. - Subset checks on sets handle ordering, duplicates and empty requirement lists.
Complexity
Let P be the number of projects, W the number of workers, S the skill-list size and k the number of tasks assigned in a round.
assign_next: O(P log P + P·W·S + k log W). TheP·W·Sterm is the worst-case subset checking, about 10^7 at the limits.register_annotatorandadd_project: O(S).add_tasks: O(number of tasks added).complete_task: O(1).- Space: O(T + W·S + P·S) for T tasks.
Reference solution
import heapq
from collections import deque
from typing import List
def simulate_dispatcher(commands: List[str], payloads: List[List]) -> List:
workers = {} # id -> {"skills": set, "cap": int, "load": int}
projects = {} # id -> {"skills": set, "prio": int, "order": int, "queue": deque}
active = {} # task_id -> worker_id
out = []
for cmd, args in zip(commands, payloads):
if cmd == "register_annotator":
wid, skills, cap = args
if wid in workers:
workers[wid]["skills"] = set(skills)
workers[wid]["cap"] = cap
else:
workers[wid] = {"skills": set(skills), "cap": cap, "load": 0}
out.append(None)
elif cmd == "add_project":
pid, skills, prio = args
if pid in projects:
projects[pid]["skills"] = set(skills)
projects[pid]["prio"] = prio
else:
projects[pid] = {
"skills": set(skills),
"prio": prio,
"order": len(projects),
"queue": deque(),
}
out.append(None)
elif cmd == "add_tasks":
pid, task_ids = args
projects[pid]["queue"].extend(task_ids)
out.append(None)
elif cmd == "assign_next":
assigned = []
order = sorted(
(p for p, info in projects.items() if info["queue"]),
key=lambda p: (-projects[p]["prio"], projects[p]["order"]),
)
for pid in order:
info = projects[pid]
need = info["skills"]
heap = [
(w["load"], wid)
for wid, w in workers.items()
if w["load"] < w["cap"] and need <= w["skills"]
]
heapq.heapify(heap)
queue = info["queue"]
while queue and heap:
load, wid = heapq.heappop(heap)
task = queue.popleft()
workers[wid]["load"] = load + 1
active[task] = wid
assigned.append([task, pid, wid])
if load + 1 < workers[wid]["cap"]:
heapq.heappush(heap, (load + 1, wid))
out.append(assigned)
elif cmd == "complete_task":
task = args[0]
if task in active:
wid = active.pop(task)
workers[wid]["load"] -= 1
out.append(True)
else:
out.append(False)
else:
raise ValueError("unknown command: " + str(cmd))
return out