Critical Path in a Task Graph

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

A multi-step workflow is represented as a list of tasks whose ordering constraints form a valid directed acyclic graph (DAG). Each item in tasks is a dictionary with three entries:

  • "name" (str): a unique identifier for that task.
  • "dependencies" (List[str]): names of prerequisite tasks that must all complete before this task may start ([] when the task can begin at time 0).
  • "duration" (int): the positive time required to finish this task once started.

Assuming unlimited tasks can run concurrently whenever their prerequisites are satisfied, implement find_critical_path(tasks) to return (critical_duration, critical_path):

  1. critical_duration (int): the largest sum of task durations along any valid dependency chain in the graph (or 0 when tasks is empty).
  2. critical_path (List[str]): the start-to-finish sequence of task names along one chain achieving critical_duration, where every task after the first directly lists its predecessor in "dependencies" (or [] when tasks is empty).

Tasks in the input list can appear in arbitrary order (not necessarily topological order), and the workflow may contain multiple starting tasks, multiple ending tasks, or separate components. When multiple dependency chains tie for the maximum total duration, returning any one of them is valid.

Examples

Example 1

Input: tasks = [
    {"name": "spec", "dependencies": [], "duration": 2},
    {"name": "ui", "dependencies": ["spec"], "duration": 3},
    {"name": "api", "dependencies": ["spec"], "duration": 6},
    {"name": "ship", "dependencies": ["ui", "api"], "duration": 4},
]
Output: (12, ["spec", "api", "ship"])

Both "ui" and "api" start at time 2 right after "spec". "ui" finishes at 5, whereas "api" finishes at 8, forcing "ship" to wait until 8 and finish at 8 + 4 = 12.

Example 2

Input: tasks = [
    {"name": "P", "dependencies": [], "duration": 9},
    {"name": "Q", "dependencies": [], "duration": 4},
    {"name": "R", "dependencies": ["P"], "duration": 1},
    {"name": "S", "dependencies": ["Q"], "duration": 8},
    {"name": "T", "dependencies": ["R", "S"], "duration": 3},
]
Output: (15, ["Q", "S", "T"])

Although "P" has a longer initial duration than "Q", "P" -> "R" -> "T" totals 9 + 1 + 3 = 13, while "Q" -> "S" -> "T" totals 4 + 8 + 3 = 15.

Example 3

Input: tasks = [
    {"name": "deploy", "dependencies": ["build"], "duration": 2},
    {"name": "lint", "dependencies": [], "duration": 3},
    {"name": "build", "dependencies": ["lint"], "duration": 4},
    {"name": "audit", "dependencies": [], "duration": 11},
]
Output: (11, ["audit"])

Even though "lint" -> "build" -> "deploy" spans three sequential tasks (3 + 4 + 2 = 9), the standalone "audit" task takes 11 time units and determines the overall bottleneck. Notice also that "deploy" appears before its prerequisites in the input list.

Example 4

Input: tasks = [
    {"name": "fetch", "dependencies": [], "duration": 5},
    {"name": "clean", "dependencies": ["fetch"], "duration": 3},
    {"name": "train", "dependencies": ["clean"], "duration": 9},
]
Output: (17, ["fetch", "clean", "train"])

Every task depends on the previous one in a single sequential pipeline of total duration 5 + 3 + 9 = 17.

Constraints

  • 0 <= len(tasks) <= 10^5
  • Total prerequisite entries across all "dependencies" lists is at most 2 * 10^5.
  • Every "name" is a unique non-empty string, and every prerequisite in "dependencies" refers to a task present in tasks.
  • 1 <= task["duration"] <= 10^9
  • The prerequisite graph is guaranteed to contain no cycles.

Step-by-step walkthrough

  1. Understand the problem and what "critical path" means

    Each task arrives as {"name": ..., "dependencies": [...], "duration": ...} inside a valid Directed Acyclic Graph (DAG)—a network of one-way prerequisite arrows with no circular loops. A task cannot start until every prerequisite in its dependencies list has finished.

    We need to return (critical_duration, critical_path):

    • critical_duration: the maximum sum of durations (not number of tasks!) along any valid prerequisite chain. Even with unlimited parallel workers, the project as a whole cannot finish any earlier than this bottleneck chain.
    • critical_path: the ordered list of task names along one longest chain from start to finish.
    Example 1 dependency graph (durations in parentheses):
    
               +---> ui (3) ----+
               |                v
      spec (2) +               ship (4)
               |                ^
               +---> api (6) ---+
    
      Chain spec -> ui  -> ship:  2 + 3 + 4 =  9
      Chain spec -> api -> ship:  2 + 6 + 4 = 12  <-- critical path! (ship waits until api finishes at t=8)
    
  2. Why greedy choices and brute-force path search fail

    Two tempting shortcuts break down right away:

    1. Greedy selection fails: Picking the heaviest starting task (or heaviest next step) is short-sighted. In Example 2, starting at P(9) gives P(9) -> R(1) -> T(3) = 13, whereas starting at the much lighter Q(4) leads to Q(4) -> S(8) -> T(3) = 15.
    2. Enumerating every path is exponential: If k diamond shapes (X -> {Y1, Y2} -> Z) are chained end to end, the graph has only 3k + 1 tasks, yet the number of start-to-end chains doubles at every diamond to 2^k. Walking every chain from scratch recomputes the downstream suffix after Z millions of times.
  3. Key idea: dynamic programming in topological order

    Instead of re-walking paths, ask one local question for each task t: what is the earliest time t can start once all of its prerequisites are done?

    • If t has no prerequisites, it can start immediately at time 0.
    • Otherwise, t must wait for its slowest prerequisite to finish:
    earliest_start[t]  = max(earliest_finish[p] for p in prerequisites of t)   (0 if none)
    earliest_finish[t] = earliest_start[t] + duration[t]
    

    And if we also record which prerequisite p achieved that maximum in best_prereq[t], we can reconstruct the entire winning chain at the end by walking backward from the last-finishing task!

    There is just one catch: to compute earliest_start[t], we need earliest_finish[p] to be 100% final for every prerequisite p of t. Processing tasks in topological order (an order where every prerequisite comes before any task that depends on it) guarantees exactly that, solving the whole graph in linear O(V + E) time.

  4. Phase 1: Build forward edges and count unmet prerequisites

    Notice two important input details:

    1. Each task lists its incoming dependencies ("ship" lists ["ui", "api"]), whereas when "ui" finishes we want to notify the tasks waiting on "ui" (ui -> ship). So we build a forward adjacency map dependents[prereq].
    2. Tasks in the input list are not guaranteed to appear in dependency order (in Example 3, "deploy" appears before "build" and "lint"). So we register every task name in a first pass before wiring edges in a second pass, while counting remaining_deps[name] (the task's in-degree, how many prerequisites it still waits on).
    def find_critical_path(tasks: List[Dict[str, object]]) -> Tuple[int, List[str]]:
        # An empty project finishes in 0 time with an empty task chain.
        if not tasks:
            return 0, []
    
        # Phase 1: Build forward dependency edges (prereq -> dependent) and in-degrees.
        # - duration_by_task: {"A": 3, "B": 2, ...}
        # - dependents: {"A": ["B", "C"], ...} tasks that directly wait for each prerequisite
        # - remaining_deps: {"A": 0, "B": 1, ...} count of prerequisites not yet finished (in-degree)
        duration_by_task = {}
        dependents = {}
        remaining_deps = {}
    
        # Register every task first because input tasks may appear before their prerequisites.
        for task in tasks:
            name = task["name"]
            duration_by_task[name] = task["duration"]
            dependents[name] = []
            remaining_deps[name] = 0
    
        for task in tasks:
            name = task["name"]
            for prereq in task["dependencies"]:
                dependents[prereq].append(name)
                remaining_deps[name] += 1
    
  5. Phases 2 & 3: Propagate finish times with Kahn's algorithm

    Kahn's algorithm produces a topological order using a FIFO queue ready_queue:

    1. Every task with remaining_deps[name] == 0 has no prerequisites, so it starts with earliest_start = 0, best_prereq = None, and enters ready_queue.
    2. When current leaves ready_queue, all of its prerequisites have already been processed, so finish_time = earliest_start[current] + duration_by_task[current] is final.
    3. For each child in dependents[current], if finish_time beats earliest_start[child] (or current is the first prerequisite reaching child), we update earliest_start[child] = finish_time and best_prereq[child] = current. Then we decrement remaining_deps[child]; the moment it hits 0, all prerequisites of child are done and child joins ready_queue.
        # Phase 2: Initialize DP tables and queue all tasks that have zero prerequisites.
        # - earliest_start[t]: longest prerequisite chain duration before task `t` can start
        # - best_prereq[t]: prerequisite right before `t` on that longest chain (None for chain starts)
        earliest_start = {}
        best_prereq = {}
        ready_queue = deque()
    
        for name in duration_by_task:
            earliest_start[name] = 0
            best_prereq[name] = None
            if remaining_deps[name] == 0:
                ready_queue.append(name)
    
        # Phase 3: Process tasks in Kahn's topological order so every prerequisite of `current`
        # is already finalized before `current` computes its finish time.
        earliest_finish = {}
    
        while ready_queue:
            current = ready_queue.popleft()
            finish_time = earliest_start[current] + duration_by_task[current]
            earliest_finish[current] = finish_time
    
            for child in dependents[current]:
                # Record `current` if it is `child`'s first seen prerequisite or strictly extends `earliest_start`.
                if best_prereq[child] is None or finish_time > earliest_start[child]:
                    earliest_start[child] = finish_time
                    best_prereq[child] = current
    
                remaining_deps[child] -= 1
                if remaining_deps[child] == 0:
                    ready_queue.append(child)
    
  6. Phase 4: Reconstruct the path and trace Example 1

    Where does the overall critical path end? At whichever task has the maximum earliest_finish across the entire workflow (not necessarily the last task in the input list—in Example 3, standalone "audit" with duration 11 beats the 3-step "lint" -> "build" -> "deploy" chain of 9!). Once we find best_end_task, we follow best_prereq backward until None and reverse the list:

        # Phase 4: Pick the task with the largest finish time overall and walk `best_prereq` backward.
        best_end_task = None
        for name in earliest_finish:
            if best_end_task is None or earliest_finish[name] > earliest_finish[best_end_task]:
                best_end_task = name
    
        critical_path = []
        cursor = best_end_task
        while cursor is not None:
            critical_path.append(cursor)
            cursor = best_prereq[cursor]
        critical_path.reverse()
    
        return earliest_finish[best_end_task], critical_path
    

    Let's trace Example 1 (spec(2) -> {ui(3), api(6)} -> ship(4)):

    Initial:
      remaining_deps = {spec: 0, ui: 1, api: 1, ship: 2}
      ready_queue    = [spec]
    
    Pop spec: earliest_finish[spec] = 0 + 2 = 2
      -> update ui:  start=2, best_prereq=spec, remaining_deps[ui]=0  -> push ui
      -> update api: start=2, best_prereq=spec, remaining_deps[api]=0 -> push api
      ready_queue = [ui, api]
    
    Pop ui: earliest_finish[ui] = 2 + 3 = 5
      -> update ship: start=5, best_prereq=ui, remaining_deps[ship]=1 (still waiting on api!)
      ready_queue = [api]
    
    Pop api: earliest_finish[api] = 2 + 6 = 8
      -> 8 > 5, so overwrite ship: start=8, best_prereq=api, remaining_deps[ship]=0 -> push ship
      ready_queue = [ship]
    
    Pop ship: earliest_finish[ship] = 8 + 4 = 12
    
    Max earliest_finish is ship (12).
    Backtrack best_prereq from ship:  ship -> api -> spec -> None
    Reverse:                          ["spec", "api", "ship"]  --> returns (12, ["spec", "api", "ship"])
    
  7. Complete solution

    Putting all four phases together gives the complete linear-time solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    
    def find_critical_path(tasks: List[Dict[str, object]]) -> Tuple[int, List[str]]:
        # An empty project finishes in 0 time with an empty task chain.
        if not tasks:
            return 0, []
    
        # Phase 1: Build forward dependency edges (prereq -> dependent) and in-degrees.
        # - duration_by_task: {"A": 3, "B": 2, ...}
        # - dependents: {"A": ["B", "C"], ...} tasks that directly wait for each prerequisite
        # - remaining_deps: {"A": 0, "B": 1, ...} count of prerequisites not yet finished (in-degree)
        duration_by_task = {}
        dependents = {}
        remaining_deps = {}
    
        # Register every task first because input tasks may appear before their prerequisites.
        for task in tasks:
            name = task["name"]
            duration_by_task[name] = task["duration"]
            dependents[name] = []
            remaining_deps[name] = 0
    
        for task in tasks:
            name = task["name"]
            for prereq in task["dependencies"]:
                dependents[prereq].append(name)
                remaining_deps[name] += 1
    
        # Phase 2: Initialize DP tables and queue all tasks that have zero prerequisites.
        # - earliest_start[t]: longest prerequisite chain duration before task `t` can start
        # - best_prereq[t]: prerequisite right before `t` on that longest chain (None for chain starts)
        earliest_start = {}
        best_prereq = {}
        ready_queue = deque()
    
        for name in duration_by_task:
            earliest_start[name] = 0
            best_prereq[name] = None
            if remaining_deps[name] == 0:
                ready_queue.append(name)
    
        # Phase 3: Process tasks in Kahn's topological order so every prerequisite of `current`
        # is already finalized before `current` computes its finish time.
        earliest_finish = {}
    
        while ready_queue:
            current = ready_queue.popleft()
            finish_time = earliest_start[current] + duration_by_task[current]
            earliest_finish[current] = finish_time
    
            for child in dependents[current]:
                # Record `current` if it is `child`'s first seen prerequisite or strictly extends `earliest_start`.
                if best_prereq[child] is None or finish_time > earliest_start[child]:
                    earliest_start[child] = finish_time
                    best_prereq[child] = current
    
                remaining_deps[child] -= 1
                if remaining_deps[child] == 0:
                    ready_queue.append(child)
    
        # Phase 4: Pick the task with the largest finish time overall and walk `best_prereq` backward.
        best_end_task = None
        for name in earliest_finish:
            if best_end_task is None or earliest_finish[name] > earliest_finish[best_end_task]:
                best_end_task = name
    
        critical_path = []
        cursor = best_end_task
        while cursor is not None:
            critical_path.append(cursor)
            cursor = best_prereq[cursor]
        critical_path.reverse()
    
        return earliest_finish[best_end_task], critical_path
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine shipping a software release with as many engineers working in parallel as you want: writing the design doc (spec, 2 days) comes first, building the frontend (ui, 3 days) and backend (api, 6 days) can run side by side right after spec, and launching (ship, 4 days) cannot begin until both ui and api are complete. Even though ui finishes on day 5, ship is held back until day 8 when api finishes—that slowest sequential chain of prerequisites is the critical path, because slipping any task along it delays the entire release. Because prerequisites form a Directed Acyclic Graph (DAG) (a network of one-way prerequisite arrows with no circular loops), we can visit tasks in topological order (an order where every prerequisite is finished before any task that depends on it) using dynamic programming (solving each task once by taking the maximum finish time among its already-solved prerequisites and saving the winning predecessor pointer).

Why do simpler strategies fail? A greedy rule that picks the heaviest starting task or heaviest immediate neighbor gets fooled whenever a lighter initial task feeds a heavier downstream chain—in Example 2, starting at P(9) yields P(9) -> R(1) -> T(3) = 13, losing to Q(4) -> S(8) -> T(3) = 15. Meanwhile, enumerating every valid chain with plain depth-first search re-traverses shared downstream tasks repeatedly, blowing up to 2^k paths on k chained diamonds (X -> {Y1, Y2} -> Z) instead of solving each task once.

Let's walk through Example 1 (spec(2) followed by ui(3) and api(6), both feeding ship(4)):

1. Seed zero-prerequisite tasks: ready_queue = [spec], earliest_start = {spec: 0, ui: 0, api: 0, ship: 0}
2. Pop spec -> finish = 0 + 2 = 2 -> ui and api both get start = 2, best_prereq = spec; ready_queue = [ui, api]
3. Pop ui   -> finish = 2 + 3 = 5 -> ship gets start = 5, best_prereq = ui (still waits on api)
4. Pop api  -> finish = 2 + 6 = 8 -> 8 > 5, so ship updates to start = 8, best_prereq = api; ready_queue = [ship]
5. Pop ship -> finish = 8 + 4 = 12 -> largest finish is ship (12); backtrack ship->api->spec -> ["spec", "api", "ship"]

Complexity

Let V be the number of tasks (len(tasks)) and E be the total number of prerequisite links across all dependencies lists.

  • Time: O(V + E). Registering tasks takes O(V), wiring dependents and in-degrees (remaining_deps, the number of incoming prerequisite edges per task) scans all E links once, Kahn's queue pops each of the V tasks once and inspects each of the E forward edges once, and scanning earliest_finish plus reversing critical_path takes O(V).
  • Space: O(V + E). The dependents adjacency dictionary stores E dependent references across V lists, while duration_by_task, remaining_deps, earliest_start, earliest_finish, best_prereq, ready_queue, and critical_path each hold at most V entries.

Edge cases

  • Empty task list (tasks = []): Handled up front by returning (0, []).
  • Single task ([{"name": "A", "dependencies": [], "duration": 5}]): Enters ready_queue immediately, finishes at 5 with best_prereq["A"] = None, and returns (5, ["A"]).
  • Unordered input list ("deploy" listed before "build" and "lint" in Example 3): Because Phase 1 registers all task names before adding edges and Phase 3 uses Kahn's topological queue, input order never affects correctness.
  • Multiple disconnected components: Every zero-prerequisite task across all components starts in ready_queue, and Phase 4 takes the maximum earliest_finish across all tasks.
  • Single heavy task beating a many-task chain: Comparing earliest_finish sums durations rather than counting hops, so "audit" (11) cleanly beats "lint" -> "build" -> "deploy" (9).
  • Multiple tied critical paths: Using strict > (finish_time > earliest_start[child]) keeps the first maximal chain encountered and always reconstructs one genuine prerequisite chain summing to critical_duration.
  • Deep linear chains (10^5 tasks): Iterative Kahn's algorithm uses a deque loop rather than recursion, avoiding Python's 1000-frame recursion limit.

Common mistakes

  • Assuming tasks is already sorted in dependency order: A single pass over tasks reads earliest_finish[prereq] before prereq has been computed whenever a task appears earlier than its prerequisites.
  • Counting hop count instead of summing durations: Plain unweighted BFS depth finds the chain with the most tasks, not the largest total duration.
  • Summing all prerequisites instead of taking their max: If "ship" waits on parallel tasks "ui" (finishing at 5) and "api" (finishing at 8), "ship" starts at max(5, 8) = 8, not 5 + 8 = 13.
  • Assuming the last task in tasks (or a single sink) ends the critical path: A workflow can have several tasks with no dependents; always pick best_end_task by maximizing earliest_finish over every task.
  • Unmemoized recursive DFS: Recomputing longest chains from scratch for every shared node turns O(V + E) into O(2^V) on diamond-heavy DAGs.
  • Reversing edge direction: prereq must finish before task, so edges point prereq -> task (though memoized top-down DP walks backward from task to its dependencies, both yield the same start-to-end chain).

Alternative approaches

  • Top-down memoized DFS: Define longest_ending_at(t) = duration[t] + max((longest_ending_at(p) for p in deps[t]), default=0) cached in a dictionary alongside best_prereq[t]. Also O(V + E) time and very concise, though deep chains exceeding ~1,000 tasks require sys.setrecursionlimit or an explicit stack in Python.
  • Shortest-path reduction with negated weights: Negating every duration turns "longest path in a DAG" into "shortest path in a DAG," which still requires topological relaxation (Dijkstra's algorithm does not work on negative edge weights!). Note that in general graphs with cycles, longest simple path is NP-hard (a class of problems with no known polynomial-time exact algorithm); the DAG guarantee is what makes O(V + E) possible.

Follow-up questions

  • How would you detect invalid inputs like dependency cycles or references to nonexistent tasks? During Phase 1, check if prereq not in dependents: before appending and raise a ValueError naming the unknown prerequisite. During Phase 3, compare how many tasks leave ready_queue against len(duration_by_task): in any cycle (such as A -> B -> A), every task on the cycle keeps remaining_deps >= 1 forever and never enters ready_queue, so len(earliest_finish) < len(duration_by_task) detects any cycle in O(V + E) time.
  • How can you identify every task that lies on at least one critical path and compute how much delay non-critical tasks can tolerate? Run a second O(V + E) pass in reverse topological order to compute latest_finish[t] = min(latest_start[c] for c in dependents[t]) (initialized to critical_duration when dependents[t] is empty) and latest_start[t] = latest_finish[t] - duration[t]. The gap slack[t] = latest_start[t] - earliest_start[t] is called slack (or total float, the maximum delay task t can absorb without pushing back project completion): every task with slack[t] == 0 sits on at least one critical path, whereas a task with slack[t] == 3 (such as "ui" in Example 1) can slip by up to 3 time units for free.
  • What changes if only k workers are available to run tasks concurrently instead of unlimited parallelism? With k bounded workers, both critical_duration and sum(durations) / k become lower bounds on project completion time, and finding the exact minimum schedule length is NP-hard even for identical-worker DAGs. In practice, schedulers use critical-path list scheduling: precompute each task's longest remaining downstream chain (critical_duration - earliest_start[t]), maintain a priority queue of ready tasks ordered by longest remaining chain first, and assign the highest-priority ready task whenever one of the k workers becomes free—a fast O((V + E) log V) heuristic guaranteed to finish within a factor of 2 - 1/k of optimal.

Follow-up questions

Similar questions

More Modular interview questions

All 1 Modular questions →