Workflow Dependency and Sequence Validator
Hard · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Implement a workflow run validator that checks whether a recorded sequence of task executions conforms to a workflow graph, a list of mandatory tasks, and extra precedence rules.
def validate_process(
process_graph: Dict[str, List[str]],
execution_sequence: List[str],
required_tasks: List[str],
ordering_rules: List[List[str]],
) -> bool:
Inputs:
- process_graph: Adjacency dictionary mapping each task ID u to the list of downstream task IDs v that depend on u (u must finish before v starts). Any task appearing either as a dictionary key or inside a downstream list belongs to the workflow.
- execution_sequence: Ordered list of task IDs in the exact chronological sequence they ran.
- required_tasks: List of mandatory task IDs that must execute during the run.
- ordering_rules: List of two-element pairs [u, v] specifying additional precedence constraints (u must finish before v starts).
Return True if and only if all of the following conditions hold (otherwise return False):
1. Known tasks & single execution: Every task in execution_sequence exists in process_graph (as a key or downstream entry) and runs at most once.
2. Mandatory coverage: Every task in required_tasks appears in execution_sequence.
3. Acyclic rule structure: Combining all directed edges from process_graph with all [u, v] pairs from ordering_rules produces no directed cycles (even among tasks that did not run).
4. Precedence satisfaction: For every directed constraint (u, v) from process_graph or ordering_rules, whenever v appears in execution_sequence, u must also appear in execution_sequence at a strictly smaller index. (Optional downstream tasks v that never ran do not trigger a violation.)
Examples
Example 1
Input:
process_graph = {"fetch": ["parse", "audit"], "parse": ["publish"], "audit": [], "publish": []}
execution_sequence = ["fetch", "audit", "parse", "publish"]
required_tasks = ["fetch", "publish"]
ordering_rules = [["audit", "parse"]]
Output:
True
Walk-through:
- Every executed task belongs to process_graph and runs once, and both mandatory tasks ("fetch" and "publish") ran.
- The combined constraints (fetch -> parse, fetch -> audit, parse -> publish, audit -> parse) contain no cycle, and every prerequisite index precedes its dependent (0 < 2, 0 < 1, 2 < 3, 1 < 2).
Example 2
Input:
process_graph = {"fetch": ["parse"], "parse": ["publish"], "publish": []}
execution_sequence = ["parse", "fetch", "publish"]
required_tasks = ["fetch", "parse", "publish"]
ordering_rules = [["fetch", "publish"]]
Output:
False
Walk-through:
- "parse" executed at index 0 before its upstream prerequisite "fetch" at index 1, violating fetch -> parse.
Example 3
Input:
process_graph = {"fetch": ["parse", "audit"], "parse": [], "audit": []}
execution_sequence = ["fetch", "parse"]
required_tasks = ["fetch", "audit"]
ordering_rules = []
Output:
False
Walk-through:
- Mandatory task "audit" is listed in required_tasks but is absent from execution_sequence.
Example 4
Input:
process_graph = {"build": ["test"], "test": ["deploy"], "deploy": []}
execution_sequence = ["build", "test", "deploy"]
required_tasks = ["build", "deploy"]
ordering_rules = [["deploy", "build"]]
Output:
False
Walk-through:
- Graph edges build -> test -> deploy combined with ordering rule ["deploy", "build"] create a directed cycle build -> test -> deploy -> build, invalidating the workflow rules.
Constraints
- Task IDs are non-empty strings.
process_graphmaps task IDs (str) to lists of downstream task IDs (List[str]); leaf tasks may appear only in downstream lists without having their own key inprocess_graph.execution_sequenceandrequired_tasksare lists of task ID strings (either or both may be empty).- Each item in
ordering_rulesis a 2-element list[before, after]of task ID strings.
Step-by-step walkthrough
Restate the problem and make every rule explicit
We are validating a recorded task log (
execution_sequence) against a workflow specification: -process_graph: an adjacency dictionary mappingtask -> [downstream_tasks](whereu -> vmeansuis a prerequisite ofv). -execution_sequence: the chronological list of tasks that actually ran. -required_tasks: mandatory tasks that must appear in the run. -ordering_rules: extra[before, after]pairs meaningbeforemust finish beforeafterstarts.Workflow: fetch -> parse -> publish (plus branch fetch -> audit, rule audit -> parse) Valid run: ['fetch', 'audit', 'parse', 'publish'] -> True Bad order: ['parse', 'fetch', 'publish'] -> False (parse ran before fetch) Missing req: ['fetch', 'parse'] (audit required) -> False (mandatory audit omitted) Cycle: build -> test -> deploy -> build -> False (circular dependency)Let's pin down the exact five checks a valid run must pass:
- Only known tasks run: Every task in
execution_sequenceexists inprocess_graph(either as a dictionary key or inside a downstream list). - No duplicate executions: Each task in
execution_sequenceruns at most once so every executed task has a single, unambiguous position. - Mandatory coverage: Every task in
required_tasksappears inexecution_sequence. - No cycles in the rules: Combined directed edges from
process_graphandordering_rulescontain zero circular dependencies (even among tasks that did not run). - Precedence holds: For every
(before, after)constraint (fromprocess_graphorordering_rules), wheneverafterran,beforemust also have run at a strictly smaller index. (Ifafternever ran, an unused optional branch breaks no rule.)
- Only known tasks run: Every task in
Build a position map in one O(n) pass
A naive validator calls
execution_sequence.count(task)andexecution_sequence.index(task)repeatedly inside loops overrequired_tasksandordering_rules. Because each list search scans up tonelements, repeated scans degrade toO(n^2 + E * n).Instead, walk
execution_sequenceonce and recordposition[task] = indexin a dictionary:execution_sequence = ['fetch', 'audit', 'parse', 'publish'] 0 1 2 3 | v position = {'fetch': 0, 'audit': 1, 'parse': 2, 'publish': 3} Now: "Did X run?" -> `X in position` O(1) "Did audit run before parse?" -> `position['audit'] < position['parse']` O(1)During that single scan, we reject unknown or repeated tasks immediately, then verify
required_tasks:def collect_known_tasks(process_graph: Dict[str, List[str]]) -> Set[str]: # Collect every node mentioned in the graph, both dictionary keys and downstream targets # (e.g. {"fetch": ["parse"]} knows both "fetch" and "parse" even when "parse" is not a key). known_tasks: Set[str] = set() for task, downstream_list in process_graph.items(): known_tasks.add(task) for next_task in downstream_list: known_tasks.add(next_task) return known_tasksknown_tasks = collect_known_tasks(process_graph) # Phase 1: Scan execution_sequence once to reject unknown or repeated tasks, # while recording each executed task's 0-based index for O(1) order lookups. position: Dict[str, int] = {} for index, task in enumerate(execution_sequence): if task not in known_tasks: return False if task in position: return False position[task] = index # Phase 2: Presence check — every required task must have executed. for req_task in required_tasks: if req_task not in position: return FalseMerge graph edges and ordering rules
A dependency edge
u -> vinprocess_graphand an ordering rule[u, v]inordering_rulesimpose the exact same precedence constraint:umust finish beforevstarts. Moreover, a cycle can span both sources — as in Example 4, wherebuild -> test -> deploycomes fromprocess_graphand["deploy", "build"]comes fromordering_rules. Merging both into a single list of(before, after)pairs lets us run cycle detection and precedence checks uniformly:def collect_constraints( process_graph: Dict[str, List[str]], ordering_rules: List[List[str]], ) -> List[Tuple[str, str]]: # Merge graph dependency edges and explicit ordering rules into one list of # (before, after) pairs where `before` must complete before `after` starts. constraints: List[Tuple[str, str]] = [] for task, downstream_list in process_graph.items(): for next_task in downstream_list: constraints.append((task, next_task)) for rule in ordering_rules: constraints.append((rule[0], rule[1])) return constraintsDetect cycles with Kahn's algorithm
A rule set is contradiction-free only when its arrows form a directed acyclic graph (DAG) — a one-way dependency network with no closed loops.
Kahn's algorithm checks for cycles iteratively (avoiding recursion-depth limits!) by tracking each task's indegree — how many incoming prerequisite arrows point to it: 1. Push every task with
indegree == 0(zero prerequisites) into a queue. 2. Pop a task from the queue, incrementremoved_count, and decrement theindegreeof each of its downstream tasks. Whenever a downstream task'sindegreedrops to0, push it into the queue. 3. Compareremoved_countagainstlen(indegree):Acyclic example: fetch -> parse -> publish Initial indegrees: fetch:0, parse:1, publish:1 queue = [fetch] Pop fetch -> lower parse to 0 queue = [parse], removed = 1 Pop parse -> lower publish to 0 queue = [publish], removed = 2 Pop publish queue = [], removed = 3 == 3 (No cycle!) Cyclic example (Example 4): build -> test -> deploy -> build Initial indegrees: build:1, test:1, deploy:1 queue = [] Loop ends immediately! removed = 0 < 3 (Cycle detected!)Even a self-loop
(u, u)givesuan initialindegreeof1, sounever enters the queue and is caught automatically.def has_cycle(constraints: List[Tuple[str, str]]) -> bool: # Kahn's algorithm peels away tasks whose unmet prerequisite count (indegree) is 0. # successors: maps task_id -> list of downstream task_ids, e.g. {"fetch": ["parse"], "parse": []} # indegree: maps task_id -> number of incoming prerequisite edges pointing to task_id successors: Dict[str, List[str]] = {} indegree: Dict[str, int] = {} for before, after in constraints: successors.setdefault(before, []).append(after) successors.setdefault(after, []) indegree.setdefault(before, 0) indegree[after] = indegree.get(after, 0) + 1 # queue: FIFO queue of tasks that currently have 0 remaining prerequisites queue = deque() for task, deg in indegree.items(): if deg == 0: queue.append(task) removed_count = 0 while queue: current = queue.popleft() removed_count += 1 for next_task in successors[current]: indegree[next_task] -= 1 if indegree[next_task] == 0: queue.append(next_task) # Tasks in a cycle (or downstream of a cycle) never reach indegree 0, # so fewer than len(indegree) tasks get removed whenever a cycle exists. return removed_count < len(indegree)Check every (before, after) constraint in O(1)
Now inspect each
(before, after)pair againstposition. Notice the asymmetry betweenafterandbefore:Workflow with two branches: fetch ---> audit (optional) | +-----> parse (ran) Case 1: execution_sequence = ['fetch', 'parse'], required = ['fetch'] - Pair (fetch, audit): audit never started -> rule "fetch before audit" is NOT violated. - Pair (fetch, parse): parse started at 1, and fetch ran at 0 < 1 -> valid! Result: True. Case 2: execution_sequence = ['parse'], required = ['parse'] - Pair (fetch, parse): parse started at 0, but prerequisite fetch never ran -> VIOLATION! Result: False.So whenever
after in position, we verify bothbefore in positionandposition[before] < position[after]:# Phase 3: Structural cycle check — graph edges + ordering rules must form a valid DAG. constraints = collect_constraints(process_graph, ordering_rules) if has_cycle(constraints): return False # Phase 4: Ordering check — if `after` started, `before` must have completed at an earlier index. # If `after` never ran (an unused optional branch), the constraint is vacuously satisfied. for before, after in constraints: if after in position: if before not in position: return False if position[before] >= position[after]: return FalseWalk through all four examples
Example 1: graph = {'fetch': ['parse', 'audit'], 'parse': ['publish'], 'audit': [], 'publish': []} seq = ['fetch', 'audit', 'parse', 'publish'], required = ['fetch', 'publish'], rules = [['audit', 'parse']] -> position = {'fetch': 0, 'audit': 1, 'parse': 2, 'publish': 3} (known, unique, required covered) -> has_cycle: False -> pairs (fetch,parse), (fetch,audit), (parse,publish), (audit,parse): 0 < 2, 0 < 1, 2 < 3, 1 < 2 -> True Example 2: seq = ['parse', 'fetch', 'publish'], rules = [['fetch', 'publish']] -> position = {'parse': 0, 'fetch': 1, 'publish': 2} -> pair ('fetch', 'parse'): 'parse' in position, 'fetch' in position, but 1 >= 0 -> False Example 3: seq = ['fetch', 'parse'], required = ['fetch', 'audit'] -> Phase 2 checks req_task = 'audit': 'audit' not in position -> False Example 4: graph = {'build': ['test'], 'test': ['deploy'], 'deploy': []}, rules = [['deploy', 'build']] -> Phase 3 runs has_cycle([('build','test'), ('test','deploy'), ('deploy','build')]): indegrees build:1, test:1, deploy:1 -> removed 0 < 3 -> True -> returns FalseComplete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque def collect_known_tasks(process_graph: Dict[str, List[str]]) -> Set[str]: # Collect every node mentioned in the graph, both dictionary keys and downstream targets # (e.g. {"fetch": ["parse"]} knows both "fetch" and "parse" even when "parse" is not a key). known_tasks: Set[str] = set() for task, downstream_list in process_graph.items(): known_tasks.add(task) for next_task in downstream_list: known_tasks.add(next_task) return known_tasks def collect_constraints( process_graph: Dict[str, List[str]], ordering_rules: List[List[str]], ) -> List[Tuple[str, str]]: # Merge graph dependency edges and explicit ordering rules into one list of # (before, after) pairs where `before` must complete before `after` starts. constraints: List[Tuple[str, str]] = [] for task, downstream_list in process_graph.items(): for next_task in downstream_list: constraints.append((task, next_task)) for rule in ordering_rules: constraints.append((rule[0], rule[1])) return constraints def has_cycle(constraints: List[Tuple[str, str]]) -> bool: # Kahn's algorithm peels away tasks whose unmet prerequisite count (indegree) is 0. # successors: maps task_id -> list of downstream task_ids, e.g. {"fetch": ["parse"], "parse": []} # indegree: maps task_id -> number of incoming prerequisite edges pointing to task_id successors: Dict[str, List[str]] = {} indegree: Dict[str, int] = {} for before, after in constraints: successors.setdefault(before, []).append(after) successors.setdefault(after, []) indegree.setdefault(before, 0) indegree[after] = indegree.get(after, 0) + 1 # queue: FIFO queue of tasks that currently have 0 remaining prerequisites queue = deque() for task, deg in indegree.items(): if deg == 0: queue.append(task) removed_count = 0 while queue: current = queue.popleft() removed_count += 1 for next_task in successors[current]: indegree[next_task] -= 1 if indegree[next_task] == 0: queue.append(next_task) # Tasks in a cycle (or downstream of a cycle) never reach indegree 0, # so fewer than len(indegree) tasks get removed whenever a cycle exists. return removed_count < len(indegree) def validate_process( process_graph: Dict[str, List[str]], execution_sequence: List[str], required_tasks: List[str], ordering_rules: List[List[str]], ) -> bool: known_tasks = collect_known_tasks(process_graph) # Phase 1: Scan execution_sequence once to reject unknown or repeated tasks, # while recording each executed task's 0-based index for O(1) order lookups. # position: maps task_id -> index in execution_sequence, e.g. {"fetch": 0, "audit": 1, "parse": 2} position: Dict[str, int] = {} for index, task in enumerate(execution_sequence): if task not in known_tasks: return False if task in position: return False position[task] = index # Phase 2: Presence check — every required task must have executed. for req_task in required_tasks: if req_task not in position: return False # Phase 3: Structural cycle check — graph edges + ordering rules must form a valid DAG. constraints = collect_constraints(process_graph, ordering_rules) if has_cycle(constraints): return False # Phase 4: Ordering check — if `after` started, `before` must have completed at an earlier index. # If `after` never ran (an unused optional branch), the constraint is vacuously satisfied. for before, after in constraints: if after in position: if before not in position: return False if position[before] >= position[after]: return False return True✅ Submit now — all tests should pass.
Intuition & how it works
Think of auditing a CI/CD build log against a pipeline recipe book: you want to confirm that every mandatory stage ran, no unknown or duplicate stage executed, every prerequisite stage finished before any dependent stage started, and the rulebook itself contains no circular "catch-22" loop (build waits for deploy while deploy waits for build). Here the workflow is supplied as an adjacency list (a dictionary mapping each task to the list of downstream tasks depending on it) alongside extra [before, after] precedence rules.
A naive implementation calls execution_sequence.index(task) and execution_sequence.count(task) repeatedly inside loops. Because each list search scans up to n items from the front, repeating it across all tasks and rules wastes O(n^2 + E * n) time. Worse, only comparing indices of tasks that both ran misses circular contradictions in the rule set (like build -> test -> deploy -> build in Example 4) and misses cases where a downstream task ran without its prerequisite ever executing.
Instead, we validate in four linear phases:
1. Scan execution_sequence once to build a dictionary position[task] = index (rejecting unknown or duplicate tasks immediately).
2. Confirm that every task in required_tasks appears in position (O(1) lookup each).
3. Merge graph edges and ordering_rules and verify they form a directed acyclic graph (DAG) (a one-way dependency network with no closed loops) via Kahn's algorithm (an iterative procedure that repeatedly strips away tasks whose indegree — the count of unmet incoming prerequisites — is 0; if any tasks remain stuck, a cycle exists).
4. Check every (before, after) pair in O(1): whenever after ran, before must also be in position with position[before] < position[after].
Walk through a compact pipeline process_graph = {'fetch': ['parse'], 'parse': ['publish'], 'publish': []} with required_tasks = ['fetch', 'publish'] and ordering_rules = []:
- On ['fetch', 'parse', 'publish']: position = {'fetch': 0, 'parse': 1, 'publish': 2} (all known, unique, and both mandatory tasks covered). Kahn's algorithm peels fetch, parse, publish (3 == 3, acyclic). Then 0 < 1 and 1 < 2 pass, returning True.
- On ['parse', 'fetch', 'publish'] (Example 2): position = {'parse': 0, 'fetch': 1, 'publish': 2}, so pair ('fetch', 'parse') fails because position['fetch'] = 1 >= position['parse'] = 0, returning False.
Complexity
Let V be the total number of distinct tasks across the graph and rules, E be the total number of graph edges plus ordering rules, n be len(execution_sequence), and r be len(required_tasks).
- Time:
O(V + E + n + r). Gathering known tasks touches every graph key and edge once (O(V + E)). Scanningexecution_sequencetakesO(n)withO(1)set/dict lookups per item, and verifyingrequired_taskstakesO(r)dictionary lookups. Kahn's algorithm visits each task and constraint at most once (O(V + E)), and checking all(before, after)pairs takesO(E)constant-time lookups. - Space:
O(V + E + n). We storeknown_tasks(O(V)),position(O(n)), the mergedconstraintslist (O(E)), and Kahn'ssuccessors,indegree, andqueuestructures (O(V + E)).
Edge cases
- Unknown task in
execution_sequence(['fetch', 'parse', 'mystery']): Rejected immediately in Phase 1 because'mystery'is absent fromknown_tasks. - Downstream-only node (
{'fetch': ['parse']}where'parse'has no own key):'parse'is still part of the workflow;collect_known_tasksgathers both keys and downstream targets. - Repeated task (
['fetch', 'parse', 'parse']): Rejected in Phase 1 as soon as the second'parse'is already present inposition. - Cycles in the graph, in the rules, or split across both: Graph chain
build -> test -> deploycombined with rule['deploy', 'build'](or a self-loop['build', 'build']) failshas_cycle, even if the cyclic tasks never ran inexecution_sequence. - Skipped prerequisite (
fetch -> parse,seq = ['parse'],required = ['parse']): Even though'fetch'was omitted fromrequired_tasks,'parse'ran without'fetch'finishing first, sobefore not in positionreturnsFalse. - Unused optional branch (
fetch -> auditandfetch -> parse,seq = ['fetch', 'parse'],required = ['fetch']): Valid (True), because'audit'never started so(fetch, audit)is vacuously satisfied. - Empty run (
graph = {},seq = [],required = [],rules = []): Valid (True); ifrequiredis non-empty whileseq = [], Phase 2 returnsFalse.
Common mistakes
- Calling
execution_sequence.index()inside the constraint loop: Each.index()scan costsO(n), inflatingEchecks toO(E * n)instead ofO(n + E). - Ignoring
process_graphedges when checking precedence or cycles: A cyclicprocess_graphwithordering_rules = []must still returnFalse. - Checking cycles separately on
process_graphandordering_rules: Both can be individually acyclic (build -> test -> deployin the graph,deploy -> buildin the rules) while forming an impossible loop together. - Only checking order when both
beforeandafterare inposition: Writingif before in position and after in position:wrongly lets['parse']pass whenfetch -> parserequires'fetch'to complete first! - Requiring both tasks in every rule to execute: If
fetch -> auditis an optional branch and'audit'was neither required nor executed,'audit'does not have to run. - Allowing duplicates to overwrite
position[task] = index: Withoutif task in position: return False,['parse', 'fetch', 'parse']overwrites'parse'to index2and masks the earlier out-of-order run at index0. - Using recursive DFS for cycle detection without raising the recursion limit: On a chain of
5,000tasks, recursive DFS hits Python's default 1,000-frameRecursionError; iterative Kahn's algorithm avoids recursion altogether.
Alternative approaches
- Streaming predecessor check (
completedset): Precomputepredecessors[after]for each task, then walkexecution_sequenceleft to right maintaining acompletedset. Whenevertaskruns, confirm everypred in predecessors[task]is already incompleted, then addtasktocompleted. This checks unknown tasks, duplicates, and precedence in one pass and aborts on the very first bad event (alongsidehas_cycleandrequired_tasks <= completed). - Iterative 3-color DFS for cycle detection: Marking nodes
0(unvisited),1(currently on the active DFS stack), and2(fully explored) on an explicit stack also detects cycles inO(V + E)time without building indegree counts.
Follow-up questions
- How would you adapt validation if new precedence rules could be inserted while a workflow run is already underway? Maintain live execution state incrementally instead of re-validating from scratch: track a
completedset of finished tasks, astartedset, and live adjacency sets (predecessorsandsuccessors). Before any task starts, verify inO(deg)time that all of its currentpredecessorsbelong tocompleted. When a dynamic rule(u, v)arrives mid-run, first run a reachability search fromvtouto reject the update if it closes a cycle, and second check whethervhas already started withoutuhaving finished beforehand (either failing the active run or pinning each run to an immutable rule-version snapshot recorded in the audit log). - How should the input model and precedence checks change when tasks execute concurrently with overlapping start and finish times? A flat list index can no longer capture overlapping tasks; instead, each executed task records an interval
(start_time, end_time)(or an event log of timestampedSTARTandENDmarkers withstart_time <= end_time). Every constraint(before, after)whereafterstarted now requiresbeforeto have finished withend_time[before] <= start_time[after], while independent branches may overlap freely (start_time[X] < end_time[Y]andstart_time[Y] < end_time[X]). Known-task, single-execution, mandatory-coverage, and Kahn's cycle checks stay unchanged. - When validating short runs against a million-node workflow graph, how can you avoid re-scanning the entire graph and abort at the first offending step? Split one-time blueprint compilation from per-run log validation: compute
known_tasks, verifyhas_cycle == False, and indexpredecessors[v]once when the graph and rules are registered (O(V + E)), caching that compiled artifact across runs. For each incomingexecution_sequence, first fail inO(1)iflen(execution_sequence) < len(required_tasks), then streamexecution_sequenceleft to right with acompletedset — immediately returningFalseon an unknown task, a duplicate task, or anypred in predecessors[task]missing fromcompleted. That inspects only executed tasks and their direct prerequisites (O(n + executed_indegrees)), never touching unexecuted regions of the million-node graph.
Follow-up questions
- How would you adapt validation if new precedence rules could be inserted while a workflow run is already underway?
- How should the input model and precedence checks change when tasks execute concurrently with overlapping start and finish times?
- When validating short runs against a million-node workflow graph, how can you avoid re-scanning the entire graph and abort at the first offending step?
Similar questions
- Zero-Downtime Production Database Migration
- Critical-Path Completion Time Across a Production DAG
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging