Reachable Task Execution Schedule

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

A build system stores task relationships in a dictionary graph: Dict[str, List[str]]. For any task u, graph[u] lists the downstream tasks that directly require u to finish before they can start (each entry v in graph[u] represents a directed prerequisite link u -> v). Tasks that have no downstream dependents may either map to [] or omit a key in graph altogether.

Implement compute_build_order(graph, start) to schedule start together with every task reachable from start along u -> v links:

def compute_build_order(graph: Dict[str, List[str]], start: str) -> Dict[str, object]:

Your schedule must obey four rules:

  1. Reachable scope only: Only schedule start and tasks reachable from start by following u -> v edges. Any task outside that reachable set—along with its outgoing edges or internal cycles—must be ignored.
  2. Prerequisite ordering: Every reachable prerequisite u of a reachable task v must appear earlier in the output list than v.
  3. Lexicographical tie-breaking: Whenever two or more reachable tasks have all of their reachable prerequisites satisfied at the same moment, choose the smallest task name next under standard ASCII/alphabetical string comparison (<).
  4. Cycle reporting: Return a dictionary with keys "order" and "has_cycle":
    • When a valid schedule exists, return {"order": [...], "has_cycle": False}.
    • When the reachable subgraph contains at least one directed cycle (including a self-loop), no complete schedule is possible; return {"order": [], "has_cycle": True}.

Examples

Example 1

  • Input: python graph = { "core": ["api", "ui"], "api": ["cli", "docs"], "ui": ["docs"], } start = "core"
  • Output: {"order": ["core", "api", "cli", "ui", "docs"], "has_cycle": False}
  • Explanation: Starting at "core" unlocks "api" and "ui". Because "api" < "ui", "api" runs next and immediately unlocks "cli". Now "cli" and "ui" are both ready; "cli" < "ui" runs first, followed by "ui", which finishes unlocking "docs".

Example 2

  • Input: python graph = { "init": ["auth"], "auth": ["db"], "db": ["auth"], } start = "init"
  • Output: {"order": [], "has_cycle": True}
  • Explanation: Both "auth" and "db" are reachable from "init" and wait on each other in a two-node loop ("auth" -> "db" -> "auth"), so no valid completion sequence exists.

Example 3

  • Input: python graph = { "lint": ["bundle"], "legacy": ["bundle", "legacy"], } start = "lint"
  • Output: {"order": ["lint", "bundle"], "has_cycle": False}
  • Explanation: Only "lint" and "bundle" can be reached from "lint". Although "legacy" has a self-loop and an edge into "bundle", "legacy" is unreachable from "lint" and is completely ignored.

Constraints

  • start and all task names in graph are non-empty strings.
  • 0 <= len(graph) <= 10^4, and the total number of dependency entries across graph is at most 5 * 10^4.
  • start may not appear as a key in graph if it has zero dependents.
  • A dependent list graph[u] may contain duplicate task names, representing repeated declarations of the same u -> v requirement.
  • Dependency chains can be several thousand tasks deep, so recursive traversals that rely on Python's default call-stack depth may fail.

Step-by-step walkthrough

  1. Understand the dependency map and return contract

    Each entry graph[u] lists the tasks that directly wait on u, so every edge u -> v means "run u before v". Given a starting task start, compute_build_order(graph, start) returns {"order": [...], "has_cycle": bool} governed by four rules:

    1. Reachable subgraph only: Schedule start together with every task reachable from start along u -> v edges. Ignore unreachable tasks, their cycles, and any incoming edges from unreachable tasks.
    2. Valid prerequisite order: Every reachable prerequisite of a task must appear earlier in order than that task.
    3. Lexicographical tie-breaking: Whenever multiple tasks have zero remaining prerequisites at the same moment, run the alphabetically smallest name next (standard Python < comparison).
    4. Cycle detection: If a dependency loop exists anywhere inside the reachable subgraph, no complete schedule exists, so return {"order": [], "has_cycle": True}.

    Also watch for leaf tasks such as "cli" and "docs" in Example 1 ({"core": ["api", "ui"], "api": ["cli", "docs"], "ui": ["docs"]}): a task with zero dependents might omit a key in graph, so we always read dependents with graph.get(task, []).

  2. Why brute-force permutations and plain queues fall short

    A brute-force oracle sorts the V reachable tasks, generates all V! permutations in lexicographical order, and returns the first permutation where every u -> v edge places u before v. That guarantees correctness on tiny inputs, but 13! already exceeds 6 billion permutations.

    What if we use a plain first-in, first-out queue, or sort ready tasks wave by wave? Both violate alphabetical tie-breaking! Look at Example 1 ({"core": ["api", "ui"], "api": ["cli", "docs"], "ui": ["docs"]}) starting from "core":

            core
           /    \
          v      v
         api     ui
        /   \   /
       v     v v
      cli   docs
    
    After "core" runs:  "api" and "ui" are ready. Pick "api" ("api" < "ui").
    After "api" runs:   "cli" becomes ready BEFORE "ui" has run!
    Now ready:          "cli" and "ui". Since "cli" < "ui", "cli" must run BEFORE "ui"!
    
    Smallest valid order:   ["core", "api", "cli", "ui", "docs"]
    Wave-by-wave mistake:   ["core", "api", "ui", "cli", "docs"]  (ran "ui" too early!)
    

    To always pop the smallest currently unlocked task—including newly unlocked tasks like "cli"—we need a dynamic priority queue (min-heap), not a FIFO queue or level-by-level batching.

  3. Phase 1: Collect only the tasks reachable from start

    First, we gather the exact set of tasks reachable from start using an iterative breadth-first search (BFS) with collections.deque. Keeping BFS iterative ensures even a chain of 10,000 tasks never hits Python's recursion limit.

    from collections import deque
    from typing import Dict, List, Set
    
    
    def collect_reachable_tasks(graph: Dict[str, List[str]], start: str) -> Set[str]:
        """Return every task reachable from `start` along `X -> dependent` edges (including `start`)."""
        # Iterative BFS avoids Python's recursion limit on deep dependency chains.
        reachable: Set[str] = {start}
        bfs_queue: deque[str] = deque([start])
    
        while bfs_queue:
            current = bfs_queue.popleft()
            # Use graph.get(...) because leaf tasks with no dependents may omit a key in `graph`.
            for dependent in graph.get(current, []):
                if dependent not in reachable:
                    reachable.add(dependent)
                    bfs_queue.append(dependent)
    
        return reachable
    
  4. Phase 2: Count prerequisites inside the reachable subgraph

    Next, for each reachable task, we count how many unfinished reachable prerequisites it is waiting on—its in-degree (unfinished_prereqs[task]).

    Be careful to count edges only from task in reachable, as illustrated in Example 3 (start = "lint"):

    start = "lint"
      lint ---> bundle <--- legacy (unreachable, also has legacy -> legacy)
    
    Reachable set = {"lint", "bundle"}
    - Counting ONLY inside reachable:  unfinished_prereqs = {"lint": 0, "bundle": 1}
                                       -> "lint" runs, "bundle" drops to 0 and runs!
    - Counting whole graph (WRONG):    unfinished_prereqs["bundle"] = 2 (from "lint" and "legacy")
                                       -> "legacy" never runs, stranding "bundle" at 1 as a fake cycle!
    

    Notice that whenever task is in reachable, every dependent in graph.get(task, []) is also in reachable by definition. And if graph[task] repeats a dependent such as "core": ["api", "api"], unfinished_prereqs["api"] increments twice here and decrements twice when "core" finishes, so "api" still unlocks cleanly once it reaches 0.

    unfinished_prereqs: Dict[str, int] = {}
    for task in reachable:
        unfinished_prereqs[task] = 0
    for task in reachable:
        for dependent in graph.get(task, []):
            unfinished_prereqs[dependent] += 1
    
  5. Phase 3: Kahn's algorithm with a min-heap and cycle detection

    Now we push every reachable task with unfinished_prereqs[task] == 0 onto ready_heap (heapq). While ready_heap is non-empty:

    1. heapq.heappop(ready_heap) pops the alphabetically smallest unlocked task and appends it to order.
    2. For each of its dependents, we decrement unfinished_prereqs[dependent] by 1; the moment a dependent drops to 0, we push it onto ready_heap.

    Why does this catch every reachable cycle? Tasks inside a cycle wait on one another ("auth" waits for "db" while "db" waits for "auth" in Example 2), so none of them ever drops to 0 unfinished prerequisites—nor does any task downstream of that cycle. Thus len(order) < len(reachable) holds at the end if and only if the reachable subgraph contains a cycle!

    import heapq
    
    ready_heap: List[str] = []
    for task in reachable:
        if unfinished_prereqs[task] == 0:
            heapq.heappush(ready_heap, task)
    
    order: List[str] = []
    while ready_heap:
        current = heapq.heappop(ready_heap)
        order.append(current)
    
        for dependent in graph.get(current, []):
            unfinished_prereqs[dependent] -= 1
            if unfinished_prereqs[dependent] == 0:
                heapq.heappush(ready_heap, dependent)
    
    if len(order) < len(reachable):
        return {"order": [], "has_cycle": True}
    return {"order": order, "has_cycle": False}
    
  6. Trace Example 1 and Example 2 step by step

    Example 1: graph = {"core": ["api", "ui"], "api": ["cli", "docs"], "ui": ["docs"]}, start = "core"
    Reachable: {"core", "api", "ui", "cli", "docs"}
    Initial unfinished_prereqs: core:0, api:1, ui:1, cli:1, docs:2
    
    Step   ready_heap (before pop)   Pop      Decrements            New 0s pushed   order so far
    -----------------------------------------------------------------------------------------------------------
      1    ["core"]                  "core"   api->0, ui->0         "api", "ui"     ["core"]
      2    ["api", "ui"]             "api"    cli->0, docs->1       "cli"           ["core", "api"]
      3    ["cli", "ui"]             "cli"    (none)                (none)          ["core", "api", "cli"]
      4    ["ui"]                    "ui"     docs->0               "docs"          ["core", "api", "cli", "ui"]
      5    ["docs"]                  "docs"   (none)                (none)          ["core", "api", "cli", "ui", "docs"]
    
    len(order) == 5 == len(reachable) -> {"order": ["core", "api", "cli", "ui", "docs"], "has_cycle": False}
    
    
    Example 2: graph = {"init": ["auth"], "auth": ["db"], "db": ["auth"]}, start = "init"
    Reachable: {"init", "auth", "db"}
    Initial unfinished_prereqs: init:0, auth:2, db:1
      Step 1: pop "init" -> auth drops 2->1 -> ready_heap = [] -> loop ends with order = ["init"]
    len(order) == 1 < 3 -> {"order": [], "has_cycle": True}
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    import heapq
    
    
    def collect_reachable_tasks(graph: Dict[str, List[str]], start: str) -> Set[str]:
        """Return every task reachable from `start` along `X -> dependent` edges (including `start`)."""
        # Iterative BFS avoids Python's recursion limit on deep dependency chains.
        reachable: Set[str] = {start}
        bfs_queue: deque[str] = deque([start])
    
        while bfs_queue:
            current = bfs_queue.popleft()
            # Use graph.get(...) because leaf tasks with no dependents may omit a key in `graph`.
            for dependent in graph.get(current, []):
                if dependent not in reachable:
                    reachable.add(dependent)
                    bfs_queue.append(dependent)
    
        return reachable
    
    
    def compute_build_order(graph: Dict[str, List[str]], start: str) -> Dict[str, object]:
        # Phase 1: Restrict our universe to tasks reachable from `start` so unreachable cycles
        # or unreachable prerequisites outside this subgraph never block reachable tasks.
        reachable = collect_reachable_tasks(graph, start)
    
        # Phase 2: Count unfinished prerequisites (in-degree) ONLY from reachable tasks.
        # unfinished_prereqs: {task: count}, e.g. {"core": 0, "api": 1, "ui": 1, "cli": 1, "docs": 2}
        # Note: duplicate entries like "core": ["api", "api"] increment "api" twice here and decrement
        # it twice when "core" runs, so "api" still unlocks once at 0.
        unfinished_prereqs: Dict[str, int] = {}
        for task in reachable:
            unfinished_prereqs[task] = 0
        for task in reachable:
            for dependent in graph.get(task, []):
                unfinished_prereqs[dependent] += 1
    
        # Phase 3: Kahn's algorithm with a min-heap (`ready_heap`) of unlocked tasks.
        # Popping the smallest string at every step produces the lexicographically smallest valid order.
        ready_heap: List[str] = []
        for task in reachable:
            if unfinished_prereqs[task] == 0:
                heapq.heappush(ready_heap, task)
    
        order: List[str] = []
        while ready_heap:
            current = heapq.heappop(ready_heap)
            order.append(current)
    
            for dependent in graph.get(current, []):
                unfinished_prereqs[dependent] -= 1
                if unfinished_prereqs[dependent] == 0:
                    heapq.heappush(ready_heap, dependent)
    
        # Phase 4: Tasks in a cycle (or waiting downstream of one) never drop to 0 unfinished
        # prerequisites, so `order` comes up short if and only if the reachable subgraph has a cycle.
        if len(order) < len(reachable):
            return {"order": [], "has_cycle": True}
        return {"order": order, "has_cycle": False}
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture assembling a software project where each finished job unlocks downstream jobs once every one of their prerequisites completes. Give each reachable task a counter tracking how many prerequisites it is still waiting on—its in-degree (the count of incoming dependency arrows inside the reachable subgraph)—and place every task whose counter starts at 0 into an alphabetically ordered inbox backed by a min-heap (a binary-tree priority queue that always removes its smallest element in O(log V) time). Repeatedly popping a zero-in-degree task, appending it to the schedule, and decrementing its dependents' counters is Kahn's algorithm (an iterative method for topological sorting, meaning ordering directed nodes so every prerequisite precedes its dependents), paired with a min-heap so ties always go to the alphabetically smallest ready task.

Why do simpler strategies break? Checking all V! permutations takes factorial time, while using a first-in, first-out queue (or sorting ready tasks wave by wave) fails alphabetical tie-breaking whenever a newly finished task unlocks a smaller name than one already waiting in the inbox. Counting in-degrees across the entire graph dictionary without restricting to reachable tasks first also breaks, because an unreachable node pointing into a reachable task keeps that task's counter above 0 forever and triggers a false cycle report.

Let's trace Example 1 (graph = {"core": ["api", "ui"], "api": ["cli", "docs"], "ui": ["docs"]}, start = "core"):

1. Reachable from "core": {"core", "api", "ui", "cli", "docs"}
   unfinished_prereqs: {"core": 0, "api": 1, "ui": 1, "cli": 1, "docs": 2}
   ready_heap: ["core"]

2. Pop "core" -> order = ["core"]
   Decrement "api" (1 -> 0) and "ui" (1 -> 0) -> ready_heap = ["api", "ui"]

3. Pop "api" (smaller than "ui") -> order = ["core", "api"]
   Decrement "cli" (1 -> 0) and "docs" (2 -> 1) -> push "cli" -> ready_heap = ["cli", "ui"]

4. Pop "cli" (smaller than "ui"!) -> order = ["core", "api", "cli"]
5. Pop "ui" -> decrement "docs" (1 -> 0) -> pop "docs"
   Final order = ["core", "api", "cli", "ui", "docs"], len(order) == 5 -> has_cycle = False

Complexity

Let V be the number of tasks reachable from start and E be the number of dependency entries in graph[task] across those V reachable tasks (treating short task-name comparisons as O(1)).

  • Time: O(E + V log V). collect_reachable_tasks visits each reachable task and outgoing link once in O(V + E) via breadth-first search (BFS) (exploring neighbors layer by layer with a FIFO queue). Counting unfinished_prereqs walks those same V tasks and E links once more in O(V + E). During Kahn's loop, each of the V tasks enters and leaves ready_heap at most once (O(log V) per heap operation, totaling O(V log V)), and each of the E links decrements a counter at most once (O(E)). Unreachable keys in graph are never scanned.
  • Space: O(V). reachable, bfs_queue, unfinished_prereqs, ready_heap, and order each store at most V task names beyond the input graph.

Edge cases

  • Single task or start omitted from graph keys: collect_reachable_tasks returns {start}, unfinished_prereqs[start] is 0, and the function returns {"order": [start], "has_cycle": False}.
  • Leaf tasks omitted from graph keys ("cli" and "docs" in Example 1): graph.get(task, []) treats missing keys as empty dependent lists.
  • Cycle passing through start ("a" -> "b" -> "a"): Even start receives unfinished_prereqs[start] >= 1, so ready_heap starts empty and immediately returns {"order": [], "has_cycle": True}.
  • Self-loop or cycle deeper in the graph ("auth" <-> "db" below "init" in Example 2): "init" runs first, but tasks on or downstream of the cycle never reach 0, leaving len(order) < len(reachable) and returning {"order": [], "has_cycle": True}.
  • Unreachable cycle or unreachable incoming edge ("legacy" in Example 3): Filtered out in Phase 1 so "bundle" only waits on reachable prerequisites.
  • Duplicate edges ("core": ["api", "api"]): "api"'s counter increments twice in Phase 2 and decrements twice when "core" finishes, pushing "api" onto ready_heap once when it hits 0.
  • Deep chains (5,000+ tasks): Both BFS and Kahn's loop are purely iterative, avoiding Python's call-stack recursion limit.

Common mistakes

  • Reversing edge direction: graph[u] lists tasks that wait on u (u runs before v), which is the reverse of [target, prerequisite] adjacency lists. Treating graph[u] as prerequisites outputs the schedule backwards.
  • Using a FIFO deque instead of heapq: Fails whenever a later-unlocked task is alphabetically smaller than an already-waiting task—for example, in {"core": ["ui", "z"], "ui": ["docs"]}, "docs" unlocks after "ui" and must run before "z".
  • Sorting ready tasks wave by wave instead of using a heap: Fails Example 1 by running the entire first wave ["api", "ui"] before "cli", producing ["core", "api", "ui", "cli", "docs"] instead of ["core", "api", "cli", "ui", "docs"].
  • Computing unfinished_prereqs across all keys in graph: Unreachable tasks never execute, so any edge from an unreachable task into reachable strands its target above 0 and causes a false cycle report on Example 3.
  • Sorting order alphabetically at the end: Breaks prerequisite ordering whenever a prerequisite is alphabetically larger than its dependent (such as "z" -> "a").

Alternative approaches

  • Iterative three-state DFS post-order: Detects cycles and builds some valid topological order in O(V + E) without heap log factors, but cannot guarantee the globally lexicographically smallest valid schedule when unlocked tasks compete across branches.
  • Lexicographical permutation search: Simple O(V! * E) brute-force oracle useful for cross-checking tiny random graphs (V <= 6) in unit tests, but intractable on realistic inputs.

Follow-up questions

  • If a cycle exists in the reachable subgraph, how would you extract and return one concrete cycle of task names? Every task left with unfinished_prereqs[task] > 0 after Kahn's loop sits either on a cycle or downstream of one, so each unscheduled task still has at least one unscheduled prerequisite inside that leftover set. Build reverse predecessor pointers restricted to leftover tasks, pick any leftover task, and step backward to an arbitrary leftover predecessor repeatedly: by the pigeonhole principle you must revisit a task within at most V steps, and reversing the slice between the two visits yields an exact directed cycle.
  • Suppose each task T takes duration[T] seconds and independent tasks can run concurrently; how do you compute the minimum total completion time? With unlimited parallel workers, run Kahn's algorithm while maintaining earliest_finish[T] (initialized to duration[T] for zero-in-degree tasks): whenever u completes, update each dependent v via earliest_finish[v] = max(earliest_finish[v], earliest_finish[u] + duration[v]). Once all reachable tasks finish, max(earliest_finish.values()) gives the minimum possible completion time, determined by the critical path (the longest duration-weighted prerequisite chain in the graph). With a fixed worker limit W, minimizing total time becomes NP-hard, so schedulers prioritize ready tasks that head the longest remaining critical path.
  • In an incremental build system where source target X just changed, how can this function identify and schedule only the stale targets? Any build artifact that transitively depends on X is potentially outdated, and that set is exact reachability from X along u -> dependent edges. Calling compute_build_order(graph, X) directly isolates the affected subgraph and returns a valid rebuild sequence while leaving untouched upstream targets out of reachable.

Follow-up questions

Similar questions

More Veeva Systems interview questions

All 1 Veeva Systems questions →