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_graph maps task IDs (str) to lists of downstream task IDs (List[str]); leaf tasks may appear only in downstream lists without having their own key in process_graph.
  • execution_sequence and required_tasks are lists of task ID strings (either or both may be empty).
  • Each item in ordering_rules is a 2-element list [before, after] of task ID strings.

Step-by-step walkthrough

  1. 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 mapping task -> [downstream_tasks] (where u -> v means u is a prerequisite of v). - 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 meaning before must finish before after starts.

    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:

    1. Only known tasks run: Every task in execution_sequence exists in process_graph (either as a dictionary key or inside a downstream list).
    2. No duplicate executions: Each task in execution_sequence runs at most once so every executed task has a single, unambiguous position.
    3. Mandatory coverage: Every task in required_tasks appears in execution_sequence.
    4. No cycles in the rules: Combined directed edges from process_graph and ordering_rules contain zero circular dependencies (even among tasks that did not run).
    5. Precedence holds: For every (before, after) constraint (from process_graph or ordering_rules), whenever after ran, before must also have run at a strictly smaller index. (If after never ran, an unused optional branch breaks no rule.)
  2. Build a position map in one O(n) pass

    A naive validator calls execution_sequence.count(task) and execution_sequence.index(task) repeatedly inside loops over required_tasks and ordering_rules. Because each list search scans up to n elements, repeated scans degrade to O(n^2 + E * n).

    Instead, walk execution_sequence once and record position[task] = index in 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_tasks
    
        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: 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
    
  3. Merge graph edges and ordering rules

    A dependency edge u -> v in process_graph and an ordering rule [u, v] in ordering_rules impose the exact same precedence constraint: u must finish before v starts. Moreover, a cycle can span both sources — as in Example 4, where build -> test -> deploy comes from process_graph and ["deploy", "build"] comes from ordering_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 constraints
    
  4. Detect 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, increment removed_count, and decrement the indegree of each of its downstream tasks. Whenever a downstream task's indegree drops to 0, push it into the queue. 3. Compare removed_count against len(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) gives u an initial indegree of 1, so u never 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)
    
  5. Check every (before, after) constraint in O(1)

    Now inspect each (before, after) pair against position. Notice the asymmetry between after and before:

    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 both before in position and position[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 False
    
  6. Walk 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 False
    
  7. Complete 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)). Scanning execution_sequence takes O(n) with O(1) set/dict lookups per item, and verifying required_tasks takes O(r) dictionary lookups. Kahn's algorithm visits each task and constraint at most once (O(V + E)), and checking all (before, after) pairs takes O(E) constant-time lookups.
  • Space: O(V + E + n). We store known_tasks (O(V)), position (O(n)), the merged constraints list (O(E)), and Kahn's successors, indegree, and queue structures (O(V + E)).

Edge cases

  • Unknown task in execution_sequence (['fetch', 'parse', 'mystery']): Rejected immediately in Phase 1 because 'mystery' is absent from known_tasks.
  • Downstream-only node ({'fetch': ['parse']} where 'parse' has no own key): 'parse' is still part of the workflow; collect_known_tasks gathers both keys and downstream targets.
  • Repeated task (['fetch', 'parse', 'parse']): Rejected in Phase 1 as soon as the second 'parse' is already present in position.
  • Cycles in the graph, in the rules, or split across both: Graph chain build -> test -> deploy combined with rule ['deploy', 'build'] (or a self-loop ['build', 'build']) fails has_cycle, even if the cyclic tasks never ran in execution_sequence.
  • Skipped prerequisite (fetch -> parse, seq = ['parse'], required = ['parse']): Even though 'fetch' was omitted from required_tasks, 'parse' ran without 'fetch' finishing first, so before not in position returns False.
  • Unused optional branch (fetch -> audit and fetch -> 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); if required is non-empty while seq = [], Phase 2 returns False.

Common mistakes

  • Calling execution_sequence.index() inside the constraint loop: Each .index() scan costs O(n), inflating E checks to O(E * n) instead of O(n + E).
  • Ignoring process_graph edges when checking precedence or cycles: A cyclic process_graph with ordering_rules = [] must still return False.
  • Checking cycles separately on process_graph and ordering_rules: Both can be individually acyclic (build -> test -> deploy in the graph, deploy -> build in the rules) while forming an impossible loop together.
  • Only checking order when both before and after are in position: Writing if before in position and after in position: wrongly lets ['parse'] pass when fetch -> parse requires 'fetch' to complete first!
  • Requiring both tasks in every rule to execute: If fetch -> audit is an optional branch and 'audit' was neither required nor executed, 'audit' does not have to run.
  • Allowing duplicates to overwrite position[task] = index: Without if task in position: return False, ['parse', 'fetch', 'parse'] overwrites 'parse' to index 2 and masks the earlier out-of-order run at index 0.
  • Using recursive DFS for cycle detection without raising the recursion limit: On a chain of 5,000 tasks, recursive DFS hits Python's default 1,000-frame RecursionError; iterative Kahn's algorithm avoids recursion altogether.

Alternative approaches

  • Streaming predecessor check (completed set): Precompute predecessors[after] for each task, then walk execution_sequence left to right maintaining a completed set. Whenever task runs, confirm every pred in predecessors[task] is already in completed, then add task to completed. This checks unknown tasks, duplicates, and precedence in one pass and aborts on the very first bad event (alongside has_cycle and required_tasks <= completed).
  • Iterative 3-color DFS for cycle detection: Marking nodes 0 (unvisited), 1 (currently on the active DFS stack), and 2 (fully explored) on an explicit stack also detects cycles in O(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 completed set of finished tasks, a started set, and live adjacency sets (predecessors and successors). Before any task starts, verify in O(deg) time that all of its current predecessors belong to completed. When a dynamic rule (u, v) arrives mid-run, first run a reachability search from v to u to reject the update if it closes a cycle, and second check whether v has already started without u having 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 timestamped START and END markers with start_time <= end_time). Every constraint (before, after) where after started now requires before to have finished with end_time[before] <= start_time[after], while independent branches may overlap freely (start_time[X] < end_time[Y] and start_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, verify has_cycle == False, and index predecessors[v] once when the graph and rules are registered (O(V + E)), caching that compiled artifact across runs. For each incoming execution_sequence, first fail in O(1) if len(execution_sequence) < len(required_tasks), then stream execution_sequence left to right with a completed set — immediately returning False on an unknown task, a duplicate task, or any pred in predecessors[task] missing from completed. 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

Similar questions

More Hadrian interview questions

All 3 Hadrian questions →