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 time0)."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):
critical_duration(int): the largest sum of task durations along any valid dependency chain in the graph (or0whentasksis empty).critical_path(List[str]): the start-to-finish sequence of task names along one chain achievingcritical_duration, where every task after the first directly lists its predecessor in"dependencies"(or[]whentasksis 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 most2 * 10^5. - Every
"name"is a unique non-empty string, and every prerequisite in"dependencies"refers to a task present intasks. 1 <= task["duration"] <= 10^9- The prerequisite graph is guaranteed to contain no cycles.
Step-by-step walkthrough
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 itsdependencieslist 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)Why greedy choices and brute-force path search fail
Two tempting shortcuts break down right away:
- Greedy selection fails: Picking the heaviest starting task (or heaviest next step) is short-sighted. In Example 2, starting at
P(9)givesP(9) -> R(1) -> T(3) = 13, whereas starting at the much lighterQ(4)leads toQ(4) -> S(8) -> T(3) = 15. - Enumerating every path is exponential: If
kdiamond shapes (X -> {Y1, Y2} -> Z) are chained end to end, the graph has only3k + 1tasks, yet the number of start-to-end chains doubles at every diamond to2^k. Walking every chain from scratch recomputes the downstream suffix afterZmillions of times.
- Greedy selection fails: Picking the heaviest starting task (or heaviest next step) is short-sighted. In Example 2, starting at
Key idea: dynamic programming in topological order
Instead of re-walking paths, ask one local question for each task
t: what is the earliest timetcan start once all of its prerequisites are done?- If
thas no prerequisites, it can start immediately at time0. - Otherwise,
tmust 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
pachieved that maximum inbest_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 needearliest_finish[p]to be 100% final for every prerequisitepoft. 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 linearO(V + E)time.- If
Phase 1: Build forward edges and count unmet prerequisites
Notice two important input details:
- 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 mapdependents[prereq]. - 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 countingremaining_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- Each task lists its incoming
Phases 2 & 3: Propagate finish times with Kahn's algorithm
Kahn's algorithm produces a topological order using a FIFO queue
ready_queue:- Every task with
remaining_deps[name] == 0has no prerequisites, so it starts withearliest_start = 0,best_prereq = None, and entersready_queue. - When
currentleavesready_queue, all of its prerequisites have already been processed, sofinish_time = earliest_start[current] + duration_by_task[current]is final. - For each
childindependents[current], iffinish_timebeatsearliest_start[child](orcurrentis the first prerequisite reachingchild), we updateearliest_start[child] = finish_timeandbest_prereq[child] = current. Then we decrementremaining_deps[child]; the moment it hits0, all prerequisites ofchildare done andchildjoinsready_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)- Every task with
Phase 4: Reconstruct the path and trace Example 1
Where does the overall critical path end? At whichever task has the maximum
earliest_finishacross the entire workflow (not necessarily the last task in the input list—in Example 3, standalone"audit"with duration11beats the 3-step"lint" -> "build" -> "deploy"chain of9!). Once we findbest_end_task, we followbest_prereqbackward untilNoneand 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_pathLet'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"])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 takesO(V), wiringdependentsand in-degrees (remaining_deps, the number of incoming prerequisite edges per task) scans allElinks once, Kahn's queue pops each of theVtasks once and inspects each of theEforward edges once, and scanningearliest_finishplus reversingcritical_pathtakesO(V). - Space:
O(V + E). Thedependentsadjacency dictionary storesEdependent references acrossVlists, whileduration_by_task,remaining_deps,earliest_start,earliest_finish,best_prereq,ready_queue, andcritical_patheach hold at mostVentries.
Edge cases
- Empty task list (
tasks = []): Handled up front by returning(0, []). - Single task (
[{"name": "A", "dependencies": [], "duration": 5}]): Entersready_queueimmediately, finishes at5withbest_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 maximumearliest_finishacross all tasks. - Single heavy task beating a many-task chain: Comparing
earliest_finishsums 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 tocritical_duration. - Deep linear chains (
10^5tasks): Iterative Kahn's algorithm uses adequeloop rather than recursion, avoiding Python's1000-frame recursion limit.
Common mistakes
- Assuming
tasksis already sorted in dependency order: A single pass overtasksreadsearliest_finish[prereq]beforeprereqhas 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 at5) and"api"(finishing at8),"ship"starts atmax(5, 8) = 8, not5 + 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 pickbest_end_taskby maximizingearliest_finishover every task. - Unmemoized recursive DFS: Recomputing longest chains from scratch for every shared node turns
O(V + E)intoO(2^V)on diamond-heavy DAGs. - Reversing edge direction:
prereqmust finish beforetask, so edges pointprereq -> task(though memoized top-down DP walks backward fromtaskto itsdependencies, 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 alongsidebest_prereq[t]. AlsoO(V + E)time and very concise, though deep chains exceeding ~1,000 tasks requiresys.setrecursionlimitor 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 aValueErrornaming the unknown prerequisite. During Phase 3, compare how many tasks leaveready_queueagainstlen(duration_by_task): in any cycle (such asA -> B -> A), every task on the cycle keepsremaining_deps >= 1forever and never entersready_queue, solen(earliest_finish) < len(duration_by_task)detects any cycle inO(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 computelatest_finish[t] = min(latest_start[c] for c in dependents[t])(initialized tocritical_durationwhendependents[t]is empty) andlatest_start[t] = latest_finish[t] - duration[t]. The gapslack[t] = latest_start[t] - earliest_start[t]is called slack (or total float, the maximum delay tasktcan absorb without pushing back project completion): every task withslack[t] == 0sits on at least one critical path, whereas a task withslack[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
kbounded workers, bothcritical_durationandsum(durations) / kbecome 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 thekworkers becomes free—a fastO((V + E) log V)heuristic guaranteed to finish within a factor of2 - 1/kof optimal.
Follow-up questions
- How would you detect invalid inputs like dependency cycles or references to nonexistent tasks?
- How can you identify every task that lies on at least one critical path and compute how much delay non-critical tasks can tolerate?
- What changes if only k workers are available to run tasks concurrently instead of unlimited parallelism?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array