Skip to main content
← PROBLEMS / CODING-ALGORITHM
An end-to-end domain learning journey

Course Schedule: Cycle Detection
& Topological Sort.

Detect circular dependencies and compute a valid execution order across 100,000+ directed tasks in O(V + E) time without overflowing Python's 1,000-frame recursion stack.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When traffic spikes expose hidden coupling, run iterative Kahn's BFS with an in-degree array for O(V + E) topological ordering, deduplicate prerequisite edges, and use iterative 3-color DFS with a parent map only when a cycle witness is needed.

TL;DR30-second simplified summary
▾

Core Mechanics: Degree audit engines, CI/CD pipelines, and workflow orchestrators validate dependency graphs of 100,000 nodes and 500,000 edges on every config push.

Visual & Structural Flow: Depicts Kahn's In-Degree Peeling + Iterative 3-Color Cycle Trace (In-Degree=0 Queue -> Processed < V -> 3-Color Iter Stack -> Back-Edge Witness); Heap-Allocated Stack State Transitions (Zero Recursion) (0: UNVISITED -> 1: VISITING -> 2: VISITED).

Trade-Offs & Production: An adjacency matrix for V = 100,000 requires 10^10 entries (tens of GB, violating the 64 MB cap). Combine two O(V + E) iterative passes (~12 MB total heap in CPython): Edge Deduplication: Deduplicate (course, prereq) pairs while building adj[prereq] and in_degree[course] in the exact same loop.

Failure Modes & Application: DAG validation and wave scheduling underpin build and orchestration systems: Workflow Orchestrators (Airflow / Temporal / Bazel): Validate task DAGs on submission and dispatch in_degree == 0 waves in parallel.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why large-scale DAG validation needs iterative O(V + E) guarantees.

Why this matters: The mechanism: understand how Why large-scale DAG validation needs iterative O(V + E) guarantees works from first principles.

Think of Why large-scale DAG validation needs iterative O(V + E) guarantees as the intuition layer for Course Schedule: Cycle Detection & Topological Sort: The mechanism: understand how Why large-scale DAG validation needs iterative O(V + E) guarantees works from first principles.

Degree audit engines, CI/CD pipelines, and workflow orchestrators validate dependency graphs of 100,000 nodes and 500,000 edges on every config push. A single circular dependency (A -> B -> C -> A) deadlocks execution, and operators need both a fast topological order on valid graphs and an exact cycle trace ([C12 -> C45 -> C89 -> C12]) when validation fails.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

RecursionError crashes and duplicate-edge false cycles.

Why this matters: The problem: see what breaks without RecursionError crashes and duplicate-edge false cycles under real concurrency or scale.

Two subtle bugs break naive graph validators at V = 100,000:

  1. Call-Stack Crash: Python's default sys.getrecursionlimit() is 1,000; a linear chain of 5,000 courses crashes recursive DFS with RecursionError.
  2. Duplicate-Edge False Positives: If [2, 1] appears twice and you deduplicate adj[1] without deduplicating in_degree[2], in_degree[2] never reaches 0 and falsely reports a cycle.
  3. Disconnected Subgraphs: Starting traversal only at node 0 misses cycles in nodes 500..505.
DAG vs. Back-Edge Cycle

Kahn's In-Degree Peeling + Iterative 3-Color Cycle Trace

In-Degree=0 QueuePeels valid DAG in O(V+E)Processed < V3-Color Iter StackPage 0Back-EdPage 2Page 3

Kahn's BFS validates DAGs in ~12 MB RAM; iterative 3-color DFS reconstructs the exact cycle only on failure.

Engineering Decision Framework
Problem
How to implement Course Schedule: Cycle Detection & Topological Sort without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When traffic spikes expose hidden coupling, run iterative Kahn's BFS with an in-degree array for O(V + E) topological ordering, deduplicate prerequisite edges, and use iterative 3-color DFS with a parent map only when a cycle witness is needed.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Course Schedule: Cycle Detection & Topological Sort experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive recursive DFS and O(V²) matrix approaches.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Think of Naive recursive DFS and O(V²) matrix approaches as the intuition layer for Course Schedule: Cycle Detection & Topological Sort: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

An adjacency matrix for V = 100,000 requires 10^10 entries (tens of GB, violating the 64 MB cap). Meanwhile, recursive DFS with sys.setrecursionlimit(200_000) risks segfaulting the OS C-stack (~8 MB limit) on deep chains.

Component Topology

Naive recursive DFS and O(V²) matrix approaches

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: Deduplicated Kahn's BFS + Iterative Cycle Witness.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Combine two O(V + E) iterative passes (~12 MB total heap in CPython):

  • Edge Deduplication: Deduplicate (course, prereq) pairs while building adj[prereq] and in_degree[course] in the exact same loop.
  • Kahn's BFS: Enqueue all nodes with in_degree == 0 (covering all disconnected components). Pop with collections.deque, append to order, and decrement neighbors. If len(order) == numCourses, return order.
  • Iterative 3-Color DFS Witness: If len(order) < numCourses, run an explicit heap stack (node, iter_idx) with states 0/1/2 and parent[] to slice out the exact minimal cycle.
Iterative 3-Color DFS

Heap-Allocated Stack State Transitions (Zero Recursion)

push (node, 0)neighbor==1 -> trace cycleall neighbors done -> pop0: UNVISITEDNot yet explored1: VISITINGOn active path; back-edg2: VISITEDSubgraph verified acycli

An explicit (node, idx) stack simulates DFS on the heap, avoiding C-stack limits on 100,000-node chains.

from collections import deque

def schedule_courses(num_courses: int, prerequisites: list[list[int]]) -> tuple[list[int], list[int]]:
    adj: list[list[int]] = [[] for _ in range(num_courses)]
    in_deg = [0] * num_courses
    seen = set()
    for course, prereq in prerequisites:
        if (prereq, course) not in seen:
            seen.add((prereq, course))
            adj[prereq].append(course)
            in_deg[course] += 1

    q = deque(i for i in range(num_courses) if in_deg[i] == 0)
    order = []
    while q:
        u = q.popleft()
        order.append(u)
        for v in adj[u]:
            in_deg[v] -= 1
            if in_deg[v] == 0:
                q.append(v)
    if len(order) == num_courses:
        return order, []

    # Iterative 3-color DFS for exact cycle witness
    state = [0] * num_courses
    parent = [-1] * num_courses
    for start in range(num_courses):
        if state[start] != 0:
            continue
        stack = [[start, 0]]
        state[start] = 1
        while stack:
            u, idx = stack[-1]
            if idx < len(adj[u]):
                v = adj[u][idx]
                stack[-1][1] += 1
                if state[v] == 0:
                    state[v] = 1
                    parent[v] = u
                    stack.append([v, 0])
                elif state[v] == 1:
                    cycle = [v]
                    cur = u
                    while cur != v:
                        cycle.append(cur)
                        cur = parent[cur]
                    cycle.append(v)
                    return [], cycle[::-1]
            else:
                state[u] = 2
                stack.pop()
    return [], []
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where topological sort and cycle detection are used.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

DAG validation and wave scheduling underpin build and orchestration systems:

  • Workflow Orchestrators (Airflow / Temporal / Bazel): Validate task DAGs on submission and dispatch in_degree == 0 waves in parallel.
  • Package Managers & Terraform: Resolve module dependency graphs and surface exact circular reference paths to users.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why is iterative Kahn's BFS paired with an explicit-stack 3-color DFS for V = 100,000 prerequisite graphs in Python?

Recommended Learning Flow