Audit a Workflow Run Against Dependencies and Precedence Rules
Trees & GraphsAuto-graded · 22 test casesLast updated
Check a run order against a task dependency graph, mandatory tasks and extra precedence pairs, while rejecting duplicates, unknown tasks and cyclic constraints.
A workflow engine records the order in which tasks were run. You must audit that record.
You are given:
workflow_graph: a dictionary mapping each task ID to a list of task IDs that depend on it (its downstream tasks). An entryu -> [v, ...]meansumust run before each listedv.run_order: a list of task IDs in the order they were run.mandatory_tasks: a list of task IDs that must appear inrun_order.precedence_pairs: a list of pairs[u, v], each meaningumust run beforev.
Return True if the run is valid, otherwise False.
Validity rules
A run is valid only if all of the following hold:
- No repeats. No task ID appears more than once in
run_order. - Known tasks only. The known tasks are every key of
workflow_graphplus every task ID listed in any of its downstream lists. Every task inrun_ordermust be a known task. - Mandatory tasks present. Every task in
mandatory_tasksappears inrun_order. - Constraint set. Build one combined set of constraints from both sources:
- one constraint
(u, v)for every edgeu -> vinworkflow_graph; - one constraint
(u, v)for every pair inprecedence_pairs.
- one constraint
- No self-constraints. No constraint may have
u == v. This applies whether or not the task was run. - Order respected. For every constraint
(u, v)where bothuandvappear inrun_order,umust appear at an earlier position thanv. If either task is absent fromrun_order, that constraint is skipped. - Acyclic constraints. The directed graph formed by all constraints must contain no cycle. This is checked over all tasks mentioned in the constraints, including tasks that were not run.
If any rule is broken, return False.
Constraints
- Task IDs are strings.
workflow_graphmay contain tasks with empty downstream lists.run_order,mandatory_tasksandprecedence_pairsmay be empty.- Each element of
precedence_pairsis a list of exactly two task IDs. - Input sizes are small enough for a linear-time solution in the total size of the inputs.
Examples
Example 1
Input: audit_workflow_run({'A': ['B'], 'B': ['C'], 'C': []}, ['A', 'B', 'C'], ['A', 'B', 'C'], [['A', 'B'], ['B', 'C']])
Output: True
Example 2
Input: audit_workflow_run({'A': ['B'], 'B': ['C'], 'C': []}, ['B', 'A', 'C'], ['A', 'B', 'C'], [['A', 'B']])
Output: False
Example 3
Input: audit_workflow_run({'A': ['B'], 'B': ['C'], 'C': []}, ['A', 'C'], ['A', 'B', 'C'], [['A', 'B']])
Output: False
Example 4
Input: audit_workflow_run({'A': ['B'], 'B': ['A']}, ['A', 'B'], ['A', 'B'], [])
Output: False
Hints
Hint 1
Build a map from task to its index in run_order in one pass. The same pass can reject duplicates and unknown tasks.
Hint 2
Merge the graph edges and the precedence pairs into one list of constraints. Then each constraint is a constant-time index comparison, applied only when both tasks were run.
Hint 3
Cycle detection is independent of run_order. Run Kahn's algorithm (or a DFS with colors) on the merged constraint graph and fail if some node is never removed.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Reject the run if
run_orderhas duplicates. Otherwise build a mappositionfrom task to index. - Build the set of known tasks (graph keys plus all downstream entries). Reject the run if any executed task is not in it.
- Reject the run if any mandatory task is missing from
position. - Merge graph edges and precedence pairs into one list of constraints
(u, v).- If
u == v, returnFalse. - If both tasks were run and
position[u] >= position[v], returnFalse. - If either task was not run, skip the constraint.
- If
- Run Kahn's topological sort on the merged constraint graph. If not every node is removed, a cycle exists, so return
False. - If every check passed, return
True.
Why it is correct
- After the duplicate and unknown-task checks,
positionis a well-defined index for every run task, so "runs before" is exactly a strict comparison of indices. - Mandatory tasks are missing exactly when they are absent from
position. - Each constraint is judged only when both endpoints ran, which matches the skip rule. Self-constraints are rejected regardless of execution.
- A cycle in the constraint graph can never be satisfied. It must still be reported when its tasks were not run, because those constraints are skipped by the index check. Kahn's algorithm removes all nodes if and only if the graph is acyclic, so it catches exactly these cases.
Complexity
Let N be the length of run_order, G the size of the graph (nodes plus edges), P the number of precedence pairs and M the number of mandatory tasks.
- Time: O(N + G + P + M).
- Space: O(N + G + P).
Reference solution
from collections import deque
from typing import Dict, List
def audit_workflow_run(workflow_graph: Dict[str, List[str]], run_order: List[str], mandatory_tasks: List[str], precedence_pairs: List[List[str]]) -> bool:
# No repeated tasks.
if len(set(run_order)) != len(run_order):
return False
position = {task: i for i, task in enumerate(run_order)}
# Known tasks: graph keys plus all downstream tasks.
known = set(workflow_graph)
for downstream in workflow_graph.values():
known.update(downstream)
if any(task not in known for task in run_order):
return False
if any(task not in position for task in mandatory_tasks):
return False
# Combined constraints.
constraints = []
for u, children in workflow_graph.items():
for v in children:
constraints.append((u, v))
for pair in precedence_pairs:
constraints.append((pair[0], pair[1]))
for u, v in constraints:
if u == v:
return False
if u in position and v in position and position[u] >= position[v]:
return False
# Cycle detection with Kahn's algorithm.
adjacency = {}
indegree = {}
for u, v in constraints:
adjacency.setdefault(u, []).append(v)
indegree.setdefault(u, 0)
indegree[v] = indegree.get(v, 0) + 1
queue = deque(node for node, d in indegree.items() if d == 0)
processed = 0
while queue:
node = queue.popleft()
processed += 1
for nxt in adjacency.get(node, []):
indegree[nxt] -= 1
if indegree[nxt] == 0:
queue.append(nxt)
return processed == len(indegree)