Schedule Dependent Tasks with Priority and Tag Exclusion
Trees & GraphsAuto-graded · 19 test casesLast updated
Tests Kahn's algorithm with deterministic tie-breaking, urgency-based heap ordering, cycle detection with path reporting, and transparent skipping of tag-excluded tasks.
You are building a task runner that dispatches work items in a safe order. Each task may depend on other tasks that must finish first, carry an urgency score, and belong to zero or more named groups.
A task is described by a dictionary with these fields:
{"id": "test", "needs": ["compile"], "urgency": 4, "tags": ["slow"]}
needs— list of task ids that must appear before this task in the output.urgency— integer priority; higher means more important.tags— optional list of string labels.
Implement:
def schedule_tasks(tasks, by_urgency=False, excluded_tags=[]) -> list[str]
Ordering rules
Default mode (by_urgency=False):
Among all tasks whose dependencies have already been scheduled, always pick the one that appears earliest in the input list. Use a min-heap keyed on input position to ensure this is deterministic.
Urgency mode (by_urgency=True):
Among ready tasks, pick the one with the highest urgency. Break ties by input position (earlier wins). Urgency never lets a task leapfrog unmet dependencies — a task only becomes a candidate once every task it needs has been scheduled.
Tag exclusion
When excluded_tags is a non-empty list, any task whose tags overlap with that list is omitted from the output. Excluded tasks are still used internally to resolve ordering: if task D needs excluded task B, and B needs task A, then D must still appear after A in the output (the excluded task acts as a transparent bridge).
The full dependency graph — including excluded tasks — must be validated and scheduled internally. Only the final output list is filtered.
Error handling
Raise a ValueError for any of these conditions:
-
Duplicate ids: two or more tasks share the same
id. -
Unknown prerequisite: a task lists a
needsentry that does not match any taskid. -
Cycle: dependencies form a loop. The error message must include one concrete cycle path, for example:
cycle: x -> z -> y -> x
Constraints
- 1 ≤ number of tasks ≤ 10⁴
- 0 ≤ number of dependency edges ≤ 10⁵
urgencyis a non-negative integer; defaults to0if omitted.tagsdefaults to[]if omitted.needsdefaults to[]if omitted.- Task ids are non-empty strings.
- Output must be fully deterministic for a given input.
- Aim for O((V + E) log V) time.
Examples
Example 1
Input: schedule_tasks([{'id': 'fetch', 'needs': [], 'urgency': 1}, {'id': 'compile', 'needs': ['fetch'], 'urgency': 3}, {'id': 'lint', 'needs': ['fetch'], 'urgency': 5, 'tags': ['style']}, {'id': 'test', 'needs': ['compile'], 'urgency': 4}, {'id': 'docs', 'needs': [], 'urgency': 2, 'tags': ['docs']}, {'id': 'package', 'needs': ['test', 'lint'], 'urgency': 2}, {'id': 'publish', 'needs': ['package', 'docs'], 'urgency': 9}], False, [])
Output: ['fetch', 'compile', 'lint', 'test', 'docs', 'package', 'publish']
Example 2
Input: schedule_tasks([{'id': 'fetch', 'needs': [], 'urgency': 1}, {'id': 'compile', 'needs': ['fetch'], 'urgency': 3}, {'id': 'lint', 'needs': ['fetch'], 'urgency': 5, 'tags': ['style']}, {'id': 'test', 'needs': ['compile'], 'urgency': 4}, {'id': 'docs', 'needs': [], 'urgency': 2, 'tags': ['docs']}, {'id': 'package', 'needs': ['test', 'lint'], 'urgency': 2}, {'id': 'publish', 'needs': ['package', 'docs'], 'urgency': 9}], True, [])
Output: ['docs', 'fetch', 'lint', 'compile', 'test', 'package', 'publish']
Example 3
Input: schedule_tasks([{'id': 'fetch', 'needs': [], 'urgency': 1}, {'id': 'compile', 'needs': ['fetch'], 'urgency': 3}, {'id': 'lint', 'needs': ['fetch'], 'urgency': 5, 'tags': ['style']}, {'id': 'test', 'needs': ['compile'], 'urgency': 4}, {'id': 'docs', 'needs': [], 'urgency': 2, 'tags': ['docs']}, {'id': 'package', 'needs': ['test', 'lint'], 'urgency': 2}, {'id': 'publish', 'needs': ['package', 'docs'], 'urgency': 9}], False, ['docs', 'style'])
Output: ['fetch', 'compile', 'test', 'package', 'publish']
Hints
Hint 1
Build an indegree count and a children map from the dependency edges, then use a heap as your ready queue — the heap key switches between input position and (-urgency, input_position) depending on the mode.
Hint 2
For cycle detection, run Kahn's algorithm to completion first: any task not in the output is part of or blocked by a cycle. Then do a DFS restricted to those leftover tasks to extract one concrete path.
Hint 3
Tag exclusion does not require a separate graph pass — schedule everything internally, then filter the output list. The internal run already respects transitive ordering through excluded tasks, so skipping them in the output is safe.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core algorithm: Kahn's topological sort
Kahn's algorithm works by tracking how many unmet prerequisites each task still has (indegree). Tasks with indegree == 0 are ready — safe to schedule immediately. After scheduling a task, decrement the indegree of everything that depends on it, and add newly-ready tasks to the frontier.
The frontier is a min-heap rather than a plain queue. This is what makes the output deterministic and mode-aware:
by_urgency=False: heap key is(input_position,)— ties are impossible, so the earliest-listed ready task always goes next.by_urgency=True: heap key is(-urgency, input_position)— highest urgency wins, input position breaks ties.
Because a task only enters the heap once all its prerequisites have been scheduled, urgency can never violate dependency order.
Cycle detection
Run Kahn's algorithm to completion first. If the output is shorter than the task list, at least one cycle exists among the unscheduled tasks. A recursive DFS over those tasks, tracking the current path and which nodes are currently on the call stack (state = 1), finds one concrete cycle. When the DFS reaches a node already on the stack, the cycle path is the slice of the current path from that node's position, plus the node itself appended again (forming the a -> b -> c -> a shape).
Tag exclusion
Excluded tasks are kept in the graph during scheduling. The internal topological order already respects all transitive dependencies, including chains that pass through excluded tasks. The only change is the final return: filter out any task whose tags overlap excluded_tags. This works correctly because the excluded tasks act as invisible waypoints — their position in the internal order enforces the right relative ordering among kept tasks without any extra bookkeeping.
Why this is correct
- Prerequisites are satisfied by construction (Kahn's invariant).
- Tie-breaking is deterministic because input positions are unique integers.
- Excluded tasks preserve ordering because they participate in the full internal scheduling run.
- Cycle paths are concrete and readable, naming actual task ids.
Complexity
- Time: O((V + E) log V) — each task and edge is processed once; each heap push/pop is O(log V).
- Space: O(V + E) for the graph, indegree array, and heap.
Reference solution
import heapq
from typing import Dict, List
def schedule_tasks(tasks: List[Dict], by_urgency: bool = False, excluded_tags: List[str] = []) -> List[str]:
if excluded_tags is None:
excluded_tags = []
# --- validation and indexing ---
ids = [task["id"] for task in tasks]
if len(set(ids)) != len(ids):
raise ValueError("duplicate task id")
index = {task_id: i for i, task_id in enumerate(ids)}
indegree = [0] * len(tasks)
children = [[] for _ in tasks]
for i, task in enumerate(tasks):
for prereq in task.get("needs", []):
if prereq not in index:
raise ValueError("unknown prerequisite: " + str(prereq))
parent = index[prereq]
indegree[i] += 1
children[parent].append(i)
# --- Kahn's algorithm with a heap frontier ---
ready = []
for i, degree in enumerate(indegree):
if degree == 0:
urgency = tasks[i].get("urgency", 0)
heap_key = (-urgency, i) if by_urgency else (i,)
heapq.heappush(ready, (heap_key, i))
order = []
while ready:
_, i = heapq.heappop(ready)
order.append(i)
for child in children[i]:
indegree[child] -= 1
if indegree[child] == 0:
urgency = tasks[child].get("urgency", 0)
heap_key = (-urgency, child) if by_urgency else (child,)
heapq.heappush(ready, (heap_key, child))
# --- cycle detection if not all tasks were scheduled ---
if len(order) != len(tasks):
state = [0] * len(tasks) # 0 = unvisited, 1 = on stack, 2 = done
path = []
position = {}
def find_cycle(node):
state[node] = 1
position[node] = len(path)
path.append(node)
for child in children[node]:
if state[child] == 0:
found = find_cycle(child)
if found:
return found
elif state[child] == 1:
return path[position[child]:] + [child]
path.pop()
position.pop(node)
state[node] = 2
return None
cycle = None
for i in range(len(tasks)):
if state[i] == 0:
cycle = find_cycle(i)
if cycle:
break
cycle_ids = [ids[i] for i in cycle]
raise ValueError("cycle: " + " -> ".join(cycle_ids))
# --- apply tag exclusion to the output only ---
excluded = set(excluded_tags)
return [ids[i] for i in order if not excluded.intersection(tasks[i].get("tags", []))]