Critical-Path Completion Time Across a Production DAG
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
A factory production job is represented as a directed acyclic graph (DAG) of discrete tasks. Each task takes a non-negative integer number of days to complete, and directed edges encode strict finish-to-start prerequisites: for an edge (prereq, next_task), work on next_task may begin only after prereq has completely finished. Every task in the graph eventually feeds into a single terminal task whose category is "shipping".
Tasks without unsatisfied prerequisites can run in parallel starting on day 0. An entry task is any node with zero incoming edges (if the "shipping" node is the only node in the job, it acts as both the entry task and the terminal task). The duration of any directed path is the sum of the task durations for all nodes along that path, including both its entry task and the "shipping" task. Category labels other than "shipping" have no effect on scheduling.
Implement work_order_lead_time to return the overall completion time of the job — the maximum duration across all directed paths from any entry task to the "shipping" node:
def work_order_lead_time(nodes: list[tuple[str, str, int]], edges: list[tuple[str, str]]) -> int:
Each tuple in nodes has the form (node_id, kind, days), and each tuple in edges has the form (prereq, next_task).
Examples
Example 1
Input:
nodes = [
("cut1", "cutting", 3),
("cut2", "cutting", 6),
("weld", "welding", 2),
("coat", "coating", 5),
("qa", "quality", 4),
("pack", "shipping", 1),
]
edges = [
("cut1", "weld"),
("cut2", "weld"),
("weld", "coat"),
("weld", "qa"),
("cut1", "qa"),
("coat", "pack"),
("qa", "pack"),
]
Output: 14
"cut1" and "cut2" have no prerequisites, so both begin on day 0. "weld" must wait for the slower of the two ("cut2" at day 6) and finishes on day 6 + 2 = 8. From "weld", "coat" finishes on day 8 + 5 = 13 while "qa" (waiting on "cut1" and "weld") finishes on day max(3, 8) + 4 = 12. Finally, "pack" begins on day max(13, 12) = 13 and finishes on day 13 + 1 = 14 along "cut2" -> "weld" -> "coat" -> "pack".
Example 2
Input:
nodes = [
("prep", "cutting", 2),
("drill", "drilling", 1),
("deburr", "finishing", 2),
("cure", "coating", 9),
("out", "shipping", 0),
]
edges = [
("prep", "drill"),
("drill", "deburr"),
("deburr", "out"),
("cure", "out"),
]
Output: 9
Although "prep" -> "drill" -> "deburr" -> "out" spans four tasks, its combined duration is 2 + 1 + 2 + 0 = 5 days, whereas "cure" -> "out" requires 9 + 0 = 9 days and governs the completion time.
Example 3
Input:
nodes = [("dispatch", "shipping", 4)]
edges = []
Output: 4
"dispatch" is the sole node in the graph, so it starts immediately and finishes after its own 4-day duration.
Constraints
1 <= len(nodes) <= 10^40 <= len(edges) <= 5 * 10^40 <= days <= 1000for every node innodes.- Every
node_idis a unique non-empty string of length at most20, and everykindis a non-empty lowercase string. - Exactly one node has
kind == "shipping", and it has zero outgoing edges. - Every
(prereq, next_task)pair connects two distinct existing node IDs, with no duplicate edges. - The graph is acyclic, and every node has at least one directed path to the
"shipping"node. - The total completion time is at most
10^7.
Step-by-step walkthrough
Understand the dependency graph and critical path
A production job forms a directed acyclic graph (DAG) — a network of one-way prerequisite arrows with no loops:
- Each node
(node_id, node_type, days)is a discrete task takingdaysdays (including0-day tasks). - Each edge
(source, target)meanstargetmust wait untilsourcefinishes. - Tasks with zero incoming edges are entry tasks (
indegree == 0) and can all launch simultaneously on day0. - Exactly one node has
node_type == "shipping", and every task eventually leads into it.
Here is Example 1 drawn with durations in parentheses:
cut1 (3) -------+-----> qa (4) ---+ \ \ ^ \ v \ / v +-> weld (2) -+---+ pack (1) ^ \ ^ / v / cut2 (6) coat (5) ------+Look at
weld (2): it waits on bothcut1 (3)andcut2 (6). Even thoughcut1finishes on day3,weldcannot begin untilcut2finishes on day6— soweldfinishes on daymax(3, 6) + 2 = 8! Whenever parallel branches converge, the slowest prerequisite dictates when the downstream step can finish. That slowest entry-to-shipping chain (cut2 -> weld -> coat -> pack = 6 + 2 + 5 + 1 = 14) is the critical path.- Each node
Why enumerating every path explodes exponentially
A tempting first attempt is to run a depth-first search from every starting node, walk every possible path to
"shipping", and keep the largest sum.Watch what happens when the graph chains just a few small "diamonds" together:
a1 a2 a30 / \ / \ / \ j0 --+ +-- j1 + +-- j2 ... --+ +-- j30 --> ship \ / \ / \ / b1 b2 b30Each diamond doubles the number of start-to-shipping paths:
30diamonds contain only92nodes, yet create2^30 > 1,000,000,000distinct paths! Walking every path re-solves the exact same suffix afterj1,j2, ...,j30millions of times. Instead, at each join nodev, we only need to remember one number: the longest finish time reachingv.Key idea: dynamic programming in topological order
Define
finish[v]as the length of the longest path starting at any starting node (indegree == 0) and ending atv(includingv's own duration):finish[v] = duration[v] if v has no incoming edges finish[v] = duration[v] + max(finish[u] for every edge u -> v) otherwiseTo compute
finish[v]cleanly in one pass, we must finish computingfinish[u]for all prerequisitesuofvbefore we finalizev. An ordering of nodes where everyucomes beforevfor each edgeu -> vis called a topological order.We generate that order iteratively using Kahn's algorithm:
- Count
indegree[v](how many prerequisites point intov) for every node. - Put all starting nodes (
indegree[v] == 0) into a queueready_queuewithfinish[v] = duration[v]. - Pop
currentfromready_queue. For each outgoing edgecurrent -> nxt, offerfinish[current] + duration[nxt]tofinish[nxt], then decrementindegree[nxt]by1. - Only when
indegree[nxt]hits0— meaning every prerequisite ofnxthas reported in — pushnxtintoready_queue!
Using an explicit queue instead of recursive DFS also avoids hitting Python's default
1000-frame recursion limit on a10,000-node chain.- Count
Build the adjacency list and in-degree counts
First scan
nodesto recordduration[node_id]and remember which ID has type"shipping". Initialize emptysuccessorslists and0in-degrees for every node (so a1-node graph withedges = [], like Example 3, still has its entry), then populate them fromedges:def work_order_lead_time( nodes: list[tuple[str, str, int]], edges: list[tuple[str, str]] ) -> int: # Phase 1: Map each node ID to its duration in days and locate the single "shipping" node. duration: Dict[str, int] = {} shipping_id: Optional[str] = None for node_id, node_type, days in nodes: duration[node_id] = days if node_type == "shipping": shipping_id = node_id # Phase 2: Build adjacency lists (`successors[u]` = list of operations waiting on `u`) # and count incoming prerequisite edges (`indegree[v]`) for every node. successors: Dict[str, List[str]] = {} indegree: Dict[str, int] = {} for node_id in duration: successors[node_id] = [] indegree[node_id] = 0 for source, target in edges: successors[source].append(target) indegree[target] += 1Propagate longest finish times with Kahn's queue
Seed
finishandready_queuewith all nodes whereindegree[node_id] == 0. Notice that non-starting nodes stay absent fromfinishuntil their first prerequisite reaches them, and each subsequent prerequisite updatesfinish[nxt]ifcandidate_time > finish[nxt]:def work_order_lead_time( nodes: list[tuple[str, str, int]], edges: list[tuple[str, str]] ) -> int: # ... Phases 1 & 2: build `duration`, `shipping_id`, `successors`, `indegree` ... # Phase 3: Seed DP and Kahn's topological queue with starting nodes (indegree == 0). finish: Dict[str, int] = {} ready_queue: deque[str] = deque() for node_id in duration: if indegree[node_id] == 0: finish[node_id] = duration[node_id] ready_queue.append(node_id) # Phase 4: Process nodes in topological order (Kahn's algorithm). while ready_queue: current = ready_queue.popleft() for nxt in successors[current]: candidate_time = finish[current] + duration[nxt] if nxt not in finish or candidate_time > finish[nxt]: finish[nxt] = candidate_time indegree[nxt] -= 1 if indegree[nxt] == 0: ready_queue.append(nxt) assert shipping_id is not None return finish[shipping_id]Once
ready_queueempties, every node in the DAG has been processed andfinish[shipping_id]holds the exact critical path length.Trace Example 1 step by step
Durations:
cut1=3, cut2=6, weld=2, coat=5, qa=4, pack=1. Initial in-degrees:cut1: 0, cut2: 0, weld: 2, coat: 1, qa: 2, pack: 2. Initial queue:['cut1', 'cut2']withfinish = {'cut1': 3, 'cut2': 6}.popped edge relaxed finish[nxt] update indegree[nxt] newly queued ----------------------------------------------------------------------------------- cut1 (3) cut1 -> weld weld = 3 + 2 = 5 2 -> 1 - cut1 -> qa qa = 3 + 4 = 7 2 -> 1 - cut2 (6) cut2 -> weld weld = max(5, 6 + 2) = 8 1 -> 0 weld weld (8) weld -> coat coat = 8 + 5 = 13 1 -> 0 coat weld -> qa qa = max(7, 8 + 4) = 12 1 -> 0 qa coat (13) coat -> pack pack = 13 + 1 = 14 2 -> 1 - qa (12) qa -> pack pack = max(14, 12 + 1) = 14 1 -> 0 pack pack (14) (no outgoing edges) queue empty!finish['pack']is14(cut2 -> weld -> coat -> pack), matching Example 1. Notice howweldwaited insideindegreeuntil bothcut1andcut2reported in before propagating8onward tocoatandqa!Complete solution
Combining the graph setup and Kahn's longest-path pass inside
work_order_lead_time:from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque def work_order_lead_time( nodes: list[tuple[str, str, int]], edges: list[tuple[str, str]] ) -> int: # Phase 1: Map each node ID to its duration in days and locate the single "shipping" node. duration: Dict[str, int] = {} shipping_id: Optional[str] = None for node_id, node_type, days in nodes: duration[node_id] = days if node_type == "shipping": shipping_id = node_id # Phase 2: Build adjacency lists (`successors[u]` = list of operations waiting on `u`) # and count incoming prerequisite edges (`indegree[v]`) for every node. successors: Dict[str, List[str]] = {} indegree: Dict[str, int] = {} for node_id in duration: successors[node_id] = [] indegree[node_id] = 0 for source, target in edges: successors[source].append(target) indegree[target] += 1 # Phase 3: Seed DP and Kahn's topological queue with starting nodes (indegree == 0). # `finish[v]` stores the longest total duration of any path from a starting node to `v` # (inclusive of both the starting node's duration and `v`'s own duration). finish: Dict[str, int] = {} ready_queue: deque[str] = deque() for node_id in duration: if indegree[node_id] == 0: finish[node_id] = duration[node_id] ready_queue.append(node_id) # Phase 4: Process nodes in topological order (Kahn's algorithm). # Because `nxt` enters `ready_queue` only when `indegree[nxt]` drops to 0, every # prerequisite of `nxt` has already offered its finish time before `nxt` is popped. while ready_queue: current = ready_queue.popleft() for nxt in successors[current]: candidate_time = finish[current] + duration[nxt] if nxt not in finish or candidate_time > finish[nxt]: finish[nxt] = candidate_time indegree[nxt] -= 1 if indegree[nxt] == 0: ready_queue.append(nxt) assert shipping_id is not None return finish[shipping_id]✅ Submit now — all tests should pass.
Intuition & how it works
Think of preparing a big holiday meal where several dishes cook in parallel, and serving the table ("shipping") cannot start until every dish is ready. If roasting the turkey takes 5 hours while chopping salad takes 1 hour, dinner waits 5 hours — whenever parallel workflows join, the slowest prerequisite sets the schedule! In project planning and factory scheduling, that slowest dependency chain is called the critical path, and the workflow itself is a DAG (directed acyclic graph — a network of one-way prerequisite arrows with no loops).
Why not trace every possible path from entry tasks to shipping, or negate durations and run Dijkstra's shortest-path algorithm? Enumerating every path re-walks shared downstream nodes over and over, exploding to 2^30 (over a billion) paths on just 30 back-to-back diamond splits (92 nodes), while Dijkstra's greedy assumption breaks on negative weights whenever a slower branch arrives at a join node later. Instead, we use dynamic programming in topological order via Kahn's algorithm (tracking each node's in-degree — its count of unfinished prerequisite arrows — and pushing a node into a queue only after its in-degree drops to 0). That way, every task v is popped after all of its prerequisites have reported their finish times, locking in finish[v] in one clean pass!
Let's trace Example 2 (prep(2) -> drill(1) -> deburr(2) -> out(0) in parallel with cure(9) -> out(0)):
Initial indegrees: prep:0, cure:0, drill:1, deburr:1, out:2
Start queue: [prep (finish=2), cure (finish=9)]
1. Pop prep (2) -> drill gets 2 + 1 = 3; indegree[drill] 1 -> 0 -> queue [cure, drill]
2. Pop cure (9) -> out gets 9 + 0 = 9; indegree[out] 2 -> 1 (out still waits on deburr!)
3. Pop drill (3) -> deburr gets 3 + 2 = 5; indegree[deburr] 1 -> 0 -> queue [deburr]
4. Pop deburr (5) -> out gets max(9, 5 + 0) = 9; indegree[out] 1 -> 0 -> queue [out]
5. Pop out -> return finish["out"] = 9
Even though prep -> drill -> deburr -> out spans more tasks (4 vs 2), cure -> out takes 9 days vs 5 days, and out waits until indegree["out"] == 0 so both branches are compared before finalizing 9.
Complexity
Let V be len(nodes) and E be len(edges).
- Time:
O(V + E). Scanningnodesand initializingsuccessorsandindegreetouches each of theVnodes a constant number of times, building the graph scans allEedges once, and Kahn's queue pushes and pops each of theVnodes once while relaxing each of theEoutgoing edges once inO(1)average dictionary time. - Space:
O(V + E).successorsstoresVkeys andEtotal edge targets across its lists, whileduration,indegree,finish, andready_queueeach hold at mostVentries.
Edge cases
- Single-node job (
[("dispatch", "shipping", 4)],edges = []):"dispatch"hasindegree == 0, entersready_queueimmediately withfinish["dispatch"] = 4, and returns4(Example 3). - Zero-day tasks (
duration == 0): Updating withif nxt not in finish or candidate_time > finish[nxt]:handles0-day totals cleanly without confusing an unvisited node with a0-day finish time. - Unordered
nodesandedges(or list elements instead of tuples):"shipping"is located by checkingnode_type == "shipping"rather than assumingnodes[-1], execution order comes purely fromindegree, and tuple unpackingfor node_id, node_type, days in nodes:accepts both tuples and 3-element lists. - Shortcut edge alongside a longer multi-step branch (
cut1 -> qaalongsidecut1 -> weld -> qa):qais not pushed intoready_queuewhencut1 -> qais relaxed becauseindegree["qa"]is still waiting onweld -> qa; whenweldlater relaxesweld -> qa,qatakesmax(...)and captures the longer path. - Deep
10,000-node chain at maximum duration (1000days each): Iterativedequeprocessing never uses the call stack (avoidingRecursionError), and the maximum total10^4 * 1000 = 10^7fits comfortably in standard integers.
Common mistakes
- Counting the number of tasks (edges) instead of summing durations: As Example 2 shows, a
2-node path of9 + 0 = 9days beats a4-node path of2 + 1 + 2 + 0 = 5days. - Forgetting to include the entry task's or
"shipping"node's own duration: Both endpoints are tasks along the path and contribute theirdurationto the total completion time. - Pushing
nxtinto the queue on the first edge that reaches it (plain BFS): Ifnxtenters the queue beforeindegree[nxt] == 0, it propagates an incompletefinish[nxt]downstream and misses slower prerequisites that arrive later. - Running Dijkstra with negated weights: Once Dijkstra pops a node, it never re-opens it, which fails when negative weights (representing longer paths) discover a better route through a slower multi-edge branch.
- Writing recursive memoized DFS without adjusting
sys.setrecursionlimit: Python's default recursion limit is1000, so a10,000-node chain crashes withRecursionError.
Alternative approaches
- Iterative memoized DFS backward from
"shipping": Buildpredecessors[v]and computelongest_to(v) = duration[v] + max(longest_to(u) for u in predecessors[v])using an explicit two-phase stack to avoid recursion limits. AlsoO(V + E)time andO(V + E)space, though iterative Kahn's forward pass is noticeably shorter and cleaner. - Bellman-Ford on negated weights: Relaxing all
EedgesV - 1times finds the longest path because a DAG has no cycles, but takesO(V * E)time — up to5 * 10^8operations at the limits instead of6 * 10^4.
Follow-up questions
- How would you reconstruct and return the exact sequence of task IDs along a critical path instead of just its total duration? Maintain a
parent: Dict[str, Optional[str]]dictionary initialized toNonefor entry tasks, and setparent[nxt] = currentwhenevercandidate_time > finish[nxt](or on first visit). Once the queue finishes, walk backward fromshipping_idviacur = parent[cur]untilNoneand reverse the collected list inO(V)time. - How could you compute each task's slack — the maximum days it can be delayed without pushing back final shipping? Slack (also called float) is computed via the Critical Path Method (CPM, a two-pass DAG scheduling algorithm pairing earliest-finish forward times with latest-finish backward times). Save the topological order from the forward pass, set
latest_finish[shipping_id] = finish[shipping_id], walk the topological list in reverse settinglatest_finish[u] = min(latest_finish[v] - duration[v] for v in successors[u]), and computeslack[u] = latest_finish[u] - finish[u]; tasks withslack[u] == 0lie on a critical path. - How would you adapt the algorithm if untrusted inputs might contain dependency cycles or disconnected tasks that never reach shipping? Kahn's algorithm detects cycles automatically: count
processed_nodespopped fromready_queue, and ifprocessed_nodes < len(duration), a cycle prevented the remaining nodes from ever reachingindegree == 0so you can raise aValueError. To exclude dead-end tasks that cannot reach"shipping", first run a reverse BFS backward fromshipping_idalong incoming edges to mark reachable tasks and restrict in-degrees and queue seeding to that reachable subgraph.
Follow-up questions
- How would you reconstruct and return the exact sequence of task IDs along a critical path instead of just its total duration?
- How could you compute each task's slack — the maximum days it can be delayed without pushing back final shipping?
- How would you adapt the algorithm if untrusted inputs might contain dependency cycles or disconnected tasks that never reach shipping?
Similar questions
- Workflow Dependency and Sequence Validator
- Zero-Downtime Production Database Migration
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance