Design a DAG task graph with cycle rejection and a deterministic execution order

Quick Overview

Implement a task dependency graph that registers tasks, rejects any dependency that would create a cycle, runs a task only after its prerequisites finish, and returns one deterministic topological order. It tests graph modeling, reachability checks, Kahn's algorithm with a min-heap and careful handling of every failure case.

Design a DAG task graph with cycle rejection and a deterministic execution order

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design a directed acyclic graph (DAG) of tasks that manages tasks and their dependencies. Each task is identified by a unique string `taskId`. A task can only be executed after every task it depends on has finished executing. The graph must always remain acyclic: any dependency that would introduce a cycle must be rejected. The system should also support querying a valid topological execution order of all currently registered tasks. When multiple tasks are ready to execute at the same time, ties are broken in lexicographic order of `taskId`, so the output is deterministic across runs. Implement a class `DAGTaskGraph` with these methods: - `addTask(taskId: str) -> bool`: register a new task. Return true if it was added, false if a task with the same id already exists. - `addDependency(taskId: str, dependsOn: str) -> bool`: declare that `taskId` depends on `dependsOn`. Return false if either task is missing, the edge already exists, or it would introduce a cycle; otherwise return true. - `execute(taskId: str) -> bool`: mark the task as executed. Return false if the task is missing, already executed, or has any unfinished prerequisite; otherwise return true. - `getExecutionOrder() -> List[str]`: return a deterministic topological ordering of all registered tasks, breaking ties by lexicographic `taskId`. Return an empty list if no tasks exist. Example 1 (a small build pipeline): ```python graph = DAGTaskGraph() graph.addTask("build") # -> True graph.addTask("test") # -> True graph.addTask("lint") # -> True graph.addTask("deploy") # -> True graph.addTask("test") # -> False (already registered) graph.addDependency("test", "build") # -> True (test depends on build) graph.addDependency("deploy", "test") # -> True graph.addDependency("deploy", "lint") # -> True graph.addDependency("deploy", "lint") # -> False (edge already exists) graph.addDependency("deploy", "docs") # -> False (docs is not a task) graph.getExecutionOrder() # -> ["build", "lint", "test", "deploy"] graph.execute("test") # -> False (build has not run) graph.execute("build") # -> True graph.execute("build") # -> False (already executed) graph.execute("test") # -> True graph.execute("deploy") # -> False (lint has not run) graph.execute("lint") # -> True graph.execute("deploy") # -> True ``` Build and lint have no prerequisites, so both are ready at the start and the tie-break places build first. Once build is placed, test becomes ready too, and lint sorts before test. Deploy needs both test and lint, so it comes last. Example 2 (a rejected cycle): ```python graph = DAGTaskGraph() # empty graph graph.addTask("a") # -> True graph.addTask("b") # -> True graph.addTask("c") # -> True graph.addDependency("b", "a") # -> True (b depends on a) graph.addDependency("c", "b") # -> True (c depends on b) graph.addDependency("a", "c") # -> False (a runs before b, b before c, so c cannot run before a) graph.getExecutionOrder() # -> ["a", "b", "c"] ``` ```hint When an edge closes a cycle The graph is acyclic before each insertion. A new edge closes a cycle only when a path already runs the other way between its two endpoints. ``` ```hint Making the order deterministic Kahn's algorithm keeps a set of tasks whose prerequisites are all placed. Choose a container for that set that always hands back the smallest id. ``` ### Constraints & Assumptions - `1 <= taskId.length <= 20` - `taskId` consists of lowercase English letters and digits. - At most ${10^4}$ calls to `addTask`. - At most ${10^5}$ calls to `addDependency`. - At most ${10^4}$ calls to `execute` and `getExecutionOrder` combined. ### Clarifying Questions to Ask - Should `getExecutionOrder` list every registered task, including tasks already executed, or only the ones still pending? - Can a dependency be added to a task that has already been executed, and should that call succeed? - Is lexicographic order plain character order, so that `"a10"` sorts before `"a9"`? - Will tasks or dependencies ever need to be removed? - How often is `getExecutionOrder` called compared with the methods that change the graph? ### What a Strong Answer Covers - A graph representation that supports both the cycle check and the prerequisite check, with the cost of each method stated. - Cycle detection at insertion time, including self-dependencies and the correct direction for the reachability search. - A topological sort whose tie-break produces exactly one order, and its complexity. - Every case where `addTask`, `addDependency` and `execute` return false. - How the design behaves near the stated limits, especially ${10^5}$ dependency insertions. ### Follow-up Questions - Each cycle check can walk the whole graph. How would you make the common case of `addDependency` cheaper? - How would you avoid recomputing the full order on every `getExecutionOrder` call? - How would you add `removeDependency` and `removeTask`? - How would you return the tasks that are ready to execute right now, in lexicographic order?

Overview: Implement a task dependency graph that registers tasks, rejects any dependency that would create a cycle, runs a task only after its prerequisites finish, and returns one deterministic topological order. It tests graph modeling, reachability checks, Kahn's algorithm with a min-heap and careful handling of every failure case.

PracHub logo
General
Nov 25, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design a directed acyclic graph (DAG) of tasks that manages tasks and their dependencies. Each task is identified by a unique string taskId. A task can only be executed after every task it depends on has finished executing.

The graph must always remain acyclic: any dependency that would introduce a cycle must be rejected. The system should also support querying a valid topological execution order of all currently registered tasks.

When multiple tasks are ready to execute at the same time, ties are broken in lexicographic order of taskId, so the output is deterministic across runs.

Implement a class DAGTaskGraph with these methods:

  • addTask(taskId: str) -> bool : register a new task. Return true if it was added, false if a task with the same id already exists.
  • addDependency(taskId: str, dependsOn: str) -> bool : declare that taskId depends on dependsOn . Return false if either task is missing, the edge already exists, or it would introduce a cycle; otherwise return true.
  • execute(taskId: str) -> bool : mark the task as executed. Return false if the task is missing, already executed, or has any unfinished prerequisite; otherwise return true.
  • getExecutionOrder() -> List[str] : return a deterministic topological ordering of all registered tasks, breaking ties by lexicographic taskId . Return an empty list if no tasks exist.

Example 1 (a small build pipeline):

graph = DAGTaskGraph()
graph.addTask("build")                   # -> True
graph.addTask("test")                    # -> True
graph.addTask("lint")                    # -> True
graph.addTask("deploy")                  # -> True
graph.addTask("test")                    # -> False (already registered)
graph.addDependency("test", "build")     # -> True  (test depends on build)
graph.addDependency("deploy", "test")    # -> True
graph.addDependency("deploy", "lint")    # -> True
graph.addDependency("deploy", "lint")    # -> False (edge already exists)
graph.addDependency("deploy", "docs")    # -> False (docs is not a task)
graph.getExecutionOrder()                # -> ["build", "lint", "test", "deploy"]
graph.execute("test")                    # -> False (build has not run)
graph.execute("build")                   # -> True
graph.execute("build")                   # -> False (already executed)
graph.execute("test")                    # -> True
graph.execute("deploy")                  # -> False (lint has not run)
graph.execute("lint")                    # -> True
graph.execute("deploy")                  # -> True

Build and lint have no prerequisites, so both are ready at the start and the tie-break places build first. Once build is placed, test becomes ready too, and lint sorts before test. Deploy needs both test and lint, so it comes last.

Example 2 (a rejected cycle):

graph = DAGTaskGraph()                   # empty graph
graph.addTask("a")                       # -> True
graph.addTask("b")                       # -> True
graph.addTask("c")                       # -> True
graph.addDependency("b", "a")            # -> True  (b depends on a)
graph.addDependency("c", "b")            # -> True  (c depends on b)
graph.addDependency("a", "c")            # -> False (a runs before b, b before c, so c cannot run before a)
graph.getExecutionOrder()                # -> ["a", "b", "c"]

Constraints & Assumptions

  • 1 <= taskId.length <= 20
  • taskId consists of lowercase English letters and digits.
  • At most 104{10^4} calls to addTask .
  • At most 105{10^5} calls to addDependency .
  • At most 104{10^4} calls to execute and getExecutionOrder combined.

Clarifying Questions to Ask Guidance

  • Should getExecutionOrder list every registered task, including tasks already executed, or only the ones still pending?
  • Can a dependency be added to a task that has already been executed, and should that call succeed?
  • Is lexicographic order plain character order, so that "a10" sorts before "a9" ?
  • Will tasks or dependencies ever need to be removed?
  • How often is getExecutionOrder called compared with the methods that change the graph?

What a Strong Answer Covers Guidance

  • A graph representation that supports both the cycle check and the prerequisite check, with the cost of each method stated.
  • Cycle detection at insertion time, including self-dependencies and the correct direction for the reachability search.
  • A topological sort whose tie-break produces exactly one order, and its complexity.
  • Every case where addTask , addDependency and execute return false.
  • How the design behaves near the stated limits, especially 105{10^5} dependency insertions.

Follow-up Questions Guidance

  • Each cycle check can walk the whole graph. How would you make the common case of addDependency cheaper?
  • How would you avoid recomputing the full order on every getExecutionOrder call?
  • How would you add removeDependency and removeTask ?
  • How would you return the tasks that are ready to execute right now, in lexicographic order?