37: CYCLE DETECTION & TOPOLOGICAL SORT — LOOPS & DEPENDENCY ORDER

A student-friendly guide to spotting cycles in graphs and ordering tasks safely with Topological Sort—explained with 10 real-time examples and Python code.

💡 Summary: Checking for Loops Before Ordering Steps

When tasks or items depend on one another, two questions come up immediately: Is there a circular dependency (a cycle)? and In what order should we do things so prerequisites come first?

A cycle means following edges brings you back to where you started—making strict prerequisite ordering impossible. A Directed Acyclic Graph (DAG) has directed edges and no cycles, so Topological Sort can arrange its vertices linearly so every edge u → v places u before v.

1. Cycle Detection & Topological Sort (Kahn's & DFS)
Here is how cycle detection and topological sorting work in practice:
  • Cycle Detection in Directed Graphs: Using 3 states during DFS—0 (unvisited), 1 (visiting / currently in recursion stack), and 2 (done)—an edge to a node in state 1 means a cycle exists.
  • Kahn's Algorithm (In-Degree + Queue): Count incoming edges (in_degree) for each node, push nodes with in_degree == 0 into a queue, pop each one into the sorted order, and reduce neighbors' in-degrees. If fewer than V nodes are output, a cycle blocked the rest.
Concept Works On What It Tells You Time Complexity
DFS Cycle Check (Directed) Directed graphs Whether a back-edge forms a loop O(V + E)
Kahn's Topological Sort Directed Acyclic Graphs (DAGs) Valid prerequisite order; also flags cycles O(V + E)
Python (cycle_and_topological_sort.py)
from collections import deque

def has_directed_cycle(nodes, adj):
    # 0 = unvisited, 1 = visiting (on stack), 2 = visited
    state = {u: 0 for u in nodes}

    def dfs(u):
        state[u] = 1
        for v in adj.get(u, []):
            if state[v] == 1:
                return True
            if state[v] == 0 and dfs(v):
                return True
        state[u] = 2
        return False

    return any(state[u] == 0 and dfs(u) for u in nodes)

def topo_sort_kahn(nodes, adj):
    in_deg = {u: 0 for u in nodes}
    for u in nodes:
        for v in adj.get(u, []):
            in_deg[v] += 1

    q = deque([u for u in nodes if in_deg[u] == 0])
    order = []

    while q:
        u = q.popleft()
        order.append(u)
        for v in adj.get(u, []):
            in_deg[v] -= 1
            if in_deg[v] == 0:
                q.append(v)

    if len(order) != len(nodes):
        return None  # Cycle detected: no valid topological order
    return order

courses = ["Math1", "Prog1", "DSA", "OS", "DBMS"]
edges = {
    "Math1": ["DSA"],
    "Prog1": ["DSA", "OS"],
    "DSA": ["DBMS"],
    "OS": [],
    "DBMS": [],
}

print("Has cycle?:", has_directed_cycle(courses, edges))
print("Course order:", topo_sort_kahn(courses, edges))
Output: Has cycle?: False Course order: ['Math1', 'Prog1', 'DSA', 'OS', 'DBMS']
2. 10 Real-Time Examples (Part 1: Examples 1 to 5)
Five real-world scenarios where cycle detection and topological sorting are used:
  • 1. College Course Prerequisites: Planning which subjects to complete first so every prerequisite is passed before its advanced course.
  • 2. Software Build & Compilation Order: Compiling helper libraries or modules before files that import them, while catching circular imports like A → B → A.
  • 3. Package Manager Dependency Resolution: Installing dependencies in a safe sequence and rejecting conflicting circular package loops.
  • 4. Spreadsheet Formula Evaluation: Recalculating cell C1 = A1 + B1 after A1 and B1, and showing a circular reference error if A1 depends on C1.
  • 5. Project & Exam Prep Task Scheduling: Ordering study topics or project milestones when some tasks cannot start until earlier ones finish.
Python (realtime_topo_cycle_1_to_5.py)
# 2. Detecting a Circular Module Import Before Running Build Steps
modules = ["config", "auth", "db", "api"]
imports = {
    "config": ["db"],
    "db": ["auth"],
    "auth": ["config"],  # Circular loop: config -> db -> auth -> config
    "api": ["auth"],
}

build_order = topo_sort_kahn(modules, imports)
print("2. Build order with circular import:", build_order)
Output: 2. Build order with circular import: None
3. 10 Real-Time Examples (Part 2: Examples 6 to 10)
Five more real-world examples showing cycles and ordering in everyday systems:
  • 6. Data Pipeline / ETL Job Stages: Running data extraction, cleaning, validation, and report generation in order so downstream jobs never read incomplete data.
  • 7. Deadlock / Circular Wait Checks: Spotting circular waiting chains among processes or locks so systems can prevent or resolve stalls.
  • 8. Manufacturing & Assembly Steps: Putting parts together in sequence where certain components must be fitted before outer covers are closed.
  • 9. CI/CD Deployment Pipelines: Running unit tests, building artifacts, staging checks, and production rollout only after earlier stages succeed.
  • 10. Recipe & Lab Experiment Steps: Following lab or cooking steps where ingredients must be prepped or heated before later steps can run.
Python (realtime_topo_cycle_6_to_10.py)
# 9. CI/CD Pipeline Stage Ordering
stages = ["checkout", "lint", "unit_test", "package", "deploy"]
deps = {
    "checkout": ["lint", "unit_test"],
    "lint": ["package"],
    "unit_test": ["package"],
    "package": ["deploy"],
    "deploy": [],
}

print("9. CI/CD execution order:", topo_sort_kahn(stages, deps))
Output: 9. CI/CD execution order: ['checkout', 'lint', 'unit_test', 'package', 'deploy']
4. Exam & Lab Tips for Students
Keep these key points in mind when revising cycle detection and topological sort:
  • Topological sort is not always unique: If multiple nodes have in_degree == 0 at the same time, different valid orders may exist.
  • Only DAGs have a topological sort: Any directed graph with a cycle cannot be topologically ordered completely.
  • Check edge direction carefully: Make sure you know whether u → v means "u comes before v" or "u requires v" before setting up adjacency lists and in-degrees.
Python (topo_cycle_checklist.py)
key_points = [
    "DAG = Directed Acyclic Graph (directed edges, zero cycles).",
    "Kahn's algorithm uses in-degrees and a queue; len(order) < V signals a cycle.",
    "Always verify edge direction before computing in-degree."
]

for item in key_points:
    print("*", item)
Output: * DAG = Directed Acyclic Graph (directed edges, zero cycles). * Kahn's algorithm uses in-degrees and a queue; len(order) < V signals a cycle. * Always verify edge direction before computing in-degree.