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:
- Reachable scope only: Only schedule
startand tasks reachable fromstartby followingu -> vedges. Any task outside that reachable set—along with its outgoing edges or internal cycles—must be ignored. - Prerequisite ordering: Every reachable prerequisite
uof a reachable taskvmust appear earlier in the output list thanv. - 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 (
<). - 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}.
- When a valid schedule exists, return
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
startand all task names ingraphare non-empty strings.0 <= len(graph) <= 10^4, and the total number of dependency entries acrossgraphis at most5 * 10^4.startmay not appear as a key ingraphif it has zero dependents.- A dependent list
graph[u]may contain duplicate task names, representing repeated declarations of the sameu -> vrequirement. - 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
Understand the dependency map and return contract
Each entry
graph[u]lists the tasks that directly wait onu, so every edgeu -> vmeans "runubeforev". Given a starting taskstart,compute_build_order(graph, start)returns{"order": [...], "has_cycle": bool}governed by four rules:- Reachable subgraph only: Schedule
starttogether with every task reachable fromstartalongu -> vedges. Ignore unreachable tasks, their cycles, and any incoming edges from unreachable tasks. - Valid prerequisite order: Every reachable prerequisite of a task must appear earlier in
orderthan that task. - Lexicographical tie-breaking: Whenever multiple tasks have zero remaining prerequisites at the same moment, run the alphabetically smallest name next (standard Python
<comparison). - 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 ingraph, so we always read dependents withgraph.get(task, []).- Reachable subgraph only: Schedule
Why brute-force permutations and plain queues fall short
A brute-force oracle sorts the
Vreachable tasks, generates allV!permutations in lexicographical order, and returns the first permutation where everyu -> vedge placesubeforev. That guarantees correctness on tiny inputs, but13!already exceeds6billion 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.Phase 1: Collect only the tasks reachable from start
First, we gather the exact set of tasks reachable from
startusing an iterative breadth-first search (BFS) withcollections.deque. Keeping BFS iterative ensures even a chain of10,000tasks 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 reachablePhase 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
taskis inreachable, everydependentingraph.get(task, [])is also inreachableby definition. And ifgraph[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 reaches0.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] += 1Phase 3: Kahn's algorithm with a min-heap and cycle detection
Now we push every reachable task with
unfinished_prereqs[task] == 0ontoready_heap(heapq). Whileready_heapis non-empty:heapq.heappop(ready_heap)pops the alphabetically smallest unlocked task and appends it toorder.- For each of its dependents, we decrement
unfinished_prereqs[dependent]by1; the moment a dependent drops to0, we push it ontoready_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 to0unfinished prerequisites—nor does any task downstream of that cycle. Thuslen(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}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}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_tasksvisits each reachable task and outgoing link once inO(V + E)via breadth-first search (BFS) (exploring neighbors layer by layer with a FIFO queue). Countingunfinished_prereqswalks those sameVtasks andElinks once more inO(V + E). During Kahn's loop, each of theVtasks enters and leavesready_heapat most once (O(log V)per heap operation, totalingO(V log V)), and each of theElinks decrements a counter at most once (O(E)). Unreachable keys ingraphare never scanned. - Space:
O(V).reachable,bfs_queue,unfinished_prereqs,ready_heap, andordereach store at mostVtask names beyond the inputgraph.
Edge cases
- Single task or
startomitted fromgraphkeys:collect_reachable_tasksreturns{start},unfinished_prereqs[start]is0, and the function returns{"order": [start], "has_cycle": False}. - Leaf tasks omitted from
graphkeys ("cli"and"docs"in Example 1):graph.get(task, [])treats missing keys as empty dependent lists. - Cycle passing through
start("a" -> "b" -> "a"): Evenstartreceivesunfinished_prereqs[start] >= 1, soready_heapstarts 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 reach0, leavinglen(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"ontoready_heaponce when it hits0. - 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 onu(uruns beforev), which is the reverse of[target, prerequisite]adjacency lists. Treatinggraph[u]as prerequisites outputs the schedule backwards. - Using a FIFO
dequeinstead ofheapq: 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_prereqsacross all keys ingraph: Unreachable tasks never execute, so any edge from an unreachable task intoreachablestrands its target above0and causes a false cycle report on Example 3. - Sorting
orderalphabetically 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] > 0after 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 reversepredecessorpointers 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 mostVsteps, 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 toduration[T]for zero-in-degree tasks): wheneverucompletes, update each dependentvviaearliest_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 limitW, 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
Xis potentially outdated, and that set is exact reachability fromXalongu -> dependentedges. Callingcompute_build_order(graph, X)directly isolates the affected subgraph and returns a valid rebuild sequence while leaving untouched upstream targets out ofreachable.
Follow-up questions
- If a cycle exists in the reachable subgraph, how would you extract and return one concrete cycle of task names?
- Suppose each task T takes duration[T] seconds and independent tasks can run concurrently; how do you compute the minimum total completion time?
- In an incremental build system where source target X just changed, how can this function identify and schedule only the stale targets?
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