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^4
  • 0 <= len(edges) <= 5 * 10^4
  • 0 <= days <= 1000 for every node in nodes.
  • Every node_id is a unique non-empty string of length at most 20, and every kind is 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

  1. 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 taking days days (including 0-day tasks).
    • Each edge (source, target) means target must wait until source finishes.
    • Tasks with zero incoming edges are entry tasks (indegree == 0) and can all launch simultaneously on day 0.
    • 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 both cut1 (3) and cut2 (6). Even though cut1 finishes on day 3, weld cannot begin until cut2 finishes on day 6 — so weld finishes on day max(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.

  2. 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                b30
    

    Each diamond doubles the number of start-to-shipping paths: 30 diamonds contain only 92 nodes, yet create 2^30 > 1,000,000,000 distinct paths! Walking every path re-solves the exact same suffix after j1, j2, ..., j30 millions of times. Instead, at each join node v, we only need to remember one number: the longest finish time reaching v.

  3. 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 at v (including v'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) otherwise
    

    To compute finish[v] cleanly in one pass, we must finish computing finish[u] for all prerequisites u of v before we finalize v. An ordering of nodes where every u comes before v for each edge u -> v is called a topological order.

    We generate that order iteratively using Kahn's algorithm:

    1. Count indegree[v] (how many prerequisites point into v) for every node.
    2. Put all starting nodes (indegree[v] == 0) into a queue ready_queue with finish[v] = duration[v].
    3. Pop current from ready_queue. For each outgoing edge current -> nxt, offer finish[current] + duration[nxt] to finish[nxt], then decrement indegree[nxt] by 1.
    4. Only when indegree[nxt] hits 0 — meaning every prerequisite of nxt has reported in — push nxt into ready_queue!

    Using an explicit queue instead of recursive DFS also avoids hitting Python's default 1000-frame recursion limit on a 10,000-node chain.

  4. Build the adjacency list and in-degree counts

    First scan nodes to record duration[node_id] and remember which ID has type "shipping". Initialize empty successors lists and 0 in-degrees for every node (so a 1-node graph with edges = [], like Example 3, still has its entry), then populate them from edges:

    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
    
  5. Propagate longest finish times with Kahn's queue

    Seed finish and ready_queue with all nodes where indegree[node_id] == 0. Notice that non-starting nodes stay absent from finish until their first prerequisite reaches them, and each subsequent prerequisite updates finish[nxt] if candidate_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_queue empties, every node in the DAG has been processed and finish[shipping_id] holds the exact critical path length.

  6. 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'] with finish = {'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'] is 14 (cut2 -> weld -> coat -> pack), matching Example 1. Notice how weld waited inside indegree until both cut1 and cut2 reported in before propagating 8 onward to coat and qa!

  7. 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). Scanning nodes and initializing successors and indegree touches each of the V nodes a constant number of times, building the graph scans all E edges once, and Kahn's queue pushes and pops each of the V nodes once while relaxing each of the E outgoing edges once in O(1) average dictionary time.
  • Space: O(V + E). successors stores V keys and E total edge targets across its lists, while duration, indegree, finish, and ready_queue each hold at most V entries.

Edge cases

  • Single-node job ([("dispatch", "shipping", 4)], edges = []): "dispatch" has indegree == 0, enters ready_queue immediately with finish["dispatch"] = 4, and returns 4 (Example 3).
  • Zero-day tasks (duration == 0): Updating with if nxt not in finish or candidate_time > finish[nxt]: handles 0-day totals cleanly without confusing an unvisited node with a 0-day finish time.
  • Unordered nodes and edges (or list elements instead of tuples): "shipping" is located by checking node_type == "shipping" rather than assuming nodes[-1], execution order comes purely from indegree, and tuple unpacking for node_id, node_type, days in nodes: accepts both tuples and 3-element lists.
  • Shortcut edge alongside a longer multi-step branch (cut1 -> qa alongside cut1 -> weld -> qa): qa is not pushed into ready_queue when cut1 -> qa is relaxed because indegree["qa"] is still waiting on weld -> qa; when weld later relaxes weld -> qa, qa takes max(...) and captures the longer path.
  • Deep 10,000-node chain at maximum duration (1000 days each): Iterative deque processing never uses the call stack (avoiding RecursionError), and the maximum total 10^4 * 1000 = 10^7 fits comfortably in standard integers.

Common mistakes

  • Counting the number of tasks (edges) instead of summing durations: As Example 2 shows, a 2-node path of 9 + 0 = 9 days beats a 4-node path of 2 + 1 + 2 + 0 = 5 days.
  • Forgetting to include the entry task's or "shipping" node's own duration: Both endpoints are tasks along the path and contribute their duration to the total completion time.
  • Pushing nxt into the queue on the first edge that reaches it (plain BFS): If nxt enters the queue before indegree[nxt] == 0, it propagates an incomplete finish[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 is 1000, so a 10,000-node chain crashes with RecursionError.

Alternative approaches

  • Iterative memoized DFS backward from "shipping": Build predecessors[v] and compute longest_to(v) = duration[v] + max(longest_to(u) for u in predecessors[v]) using an explicit two-phase stack to avoid recursion limits. Also O(V + E) time and O(V + E) space, though iterative Kahn's forward pass is noticeably shorter and cleaner.
  • Bellman-Ford on negated weights: Relaxing all E edges V - 1 times finds the longest path because a DAG has no cycles, but takes O(V * E) time — up to 5 * 10^8 operations at the limits instead of 6 * 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 to None for entry tasks, and set parent[nxt] = current whenever candidate_time > finish[nxt] (or on first visit). Once the queue finishes, walk backward from shipping_id via cur = parent[cur] until None and reverse the collected list in O(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 setting latest_finish[u] = min(latest_finish[v] - duration[v] for v in successors[u]), and compute slack[u] = latest_finish[u] - finish[u]; tasks with slack[u] == 0 lie 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_nodes popped from ready_queue, and if processed_nodes < len(duration), a cycle prevented the remaining nodes from ever reaching indegree == 0 so you can raise a ValueError. To exclude dead-end tasks that cannot reach "shipping", first run a reverse BFS backward from shipping_id along incoming edges to mark reachable tasks and restrict in-degrees and queue seeding to that reachable subgraph.

Follow-up questions

Similar questions

More Hadrian interview questions

All 3 Hadrian questions →