{"post":{"slug":"what-is-topological-sort-2026","title":"What Is Topological Sort? 2026 Guide","excerpt":"Topological sort takes a directed acyclic graph and lays its nodes out in a line where every dependency comes before whatever needs it. Here is how it works and where it breaks.","category":"code","date":"July 24, 2026","author":"ByteLedger Team","content":"<span class=\"dropcap\">T</span>opological sort takes a [directed acyclic graph](/blog/what-is-a-directed-acyclic-graph-2026) and produces a line-up of its nodes where every edge points forward: if there is an edge from A to B, A appears before B in the result. It is the algorithm behind every \"figure out what order to run these steps in\" problem, from installing packages to compiling a spreadsheet formula by formula.\n\n## What changed in 2026\n\n- **Package managers lean on it more visibly.** As dependency graphs grow deeper across monorepos and multi-language projects, more tools surface the resolved install order directly, rather than hiding it as an implementation detail — useful when a bad conflict needs debugging.\n- **Task orchestrators expose the ordering, not just the result.** Modern pipeline tools increasingly let you inspect the computed topological order before execution, so you can catch a wrong dependency before it runs rather than after.\n- **Parallel scheduling got more attention.** Because a topological order is rarely unique, schedulers increasingly exploit that freedom to run independent branches of the DAG concurrently instead of processing everything strictly in one line.\n\n## The two standard algorithms\n\n**Kahn approach (queue-based).** Count the incoming edges for every node. Put every node with zero incoming edges in a queue. Repeatedly pop a node, add it to the result, and decrement the incoming-edge count of its neighbors — any neighbor that drops to zero joins the queue. If the queue empties before every node has been processed, the graph has a cycle.\n\n```python\nfrom collections import deque\n\ndef topological_sort(graph):\n    indegree = {n: 0 for n in graph}\n    for n in graph:\n        for m in graph[n]:\n            indegree[m] += 1\n\n    queue = deque(n for n in indegree if indegree[n] == 0)\n    order = []\n    while queue:\n        node = queue.popleft()\n        order.append(node)\n        for neighbor in graph[node]:\n            indegree[neighbor] -= 1\n            if indegree[neighbor] == 0:\n                queue.append(neighbor)\n\n    if len(order) != len(graph):\n        raise ValueError(\"graph has a cycle\")\n    return order\n```\n\n**DFS-based sort.** Run a depth-first search from every unvisited node, and once a node has no more unvisited neighbors to explore, push it onto a stack. Reverse the stack at the end. It works because a node only gets pushed after everything reachable from it has already been pushed.\n\nBoth produce a valid order. Neither is \"more correct\" than the other — pick Kahn when you also want cycle detection and parallel-batch information for free, and DFS-based sort when you are already doing a DFS pass for another reason.\n\n## Comparing the two approaches\n\n| Approach | How it works | Detects cycles as a side effect | Natural fit for |\n| --- | --- | --- | --- |\n| Kahn (queue) | Repeatedly remove zero-indegree nodes | Yes — leftover nodes mean a cycle | Parallel scheduling, build systems |\n| DFS-based | Postorder traversal, then reverse | Yes, with a gray/visiting marker | Compilers, single-pass static analysis |\n\n## Why the order is not unique\n\nIf a graph has two nodes that do not depend on each other at all, either can legally come first. A build system with ten independent packages has 10-factorial valid orders. This is a feature: it is exactly the freedom a scheduler needs to run those ten packages in parallel instead of picking an arbitrary sequence and serializing everything.\n\n## Common mistakes\n\n**Forgetting to check for a cycle at all.** A naive implementation can silently return a partial or wrong order instead of failing loudly on a graph that was never a valid DAG to begin with.\n\n**Assuming the topological order is the fastest execution order.** Order determines correctness, not speed. Combine it with knowledge of which branches are independent if you actually want to parallelize.\n\n**Re-sorting after every small graph change.** For a graph that changes incrementally (adding one task at a time), a full re-sort is wasteful. Incremental algorithms exist for that case — reach for one before assuming a full re-run is required.\n\n## FAQ\n\n**Does topological sort work on an undirected graph?**\nNo. The whole concept depends on edges having a direction, which is what defines \"comes before.\"\n\n**What happens if I run it on a graph with a cycle?**\nA correct implementation should detect this and fail explicitly rather than return a silently wrong order. Both the Kahn and DFS approaches can be adapted to report the cycle.\n\n**Is topological sort the same as sorting numbers?**\nNo. Numeric sorting has one correct output. Topological sort usually has many valid outputs; it only enforces relative order between connected nodes.\n\n**Which is faster, Kahn or DFS-based sort?**\nBoth run in linear time relative to the number of nodes and edges. In practice, pick based on what else your pipeline is already doing, not on raw speed.\n\n## Where to go next\n\n- [What is a directed acyclic graph in 2026](/blog/what-is-a-directed-acyclic-graph-2026)\n- [What is union-find in 2026](/blog/what-is-union-find-2026)\n- [What is a segment tree in 2026](/blog/what-is-a-segment-tree-2026)","hue":260,"metaTitle":"Topological Sort Explained 2026","metaDescription":"What is topological sort in 2026? A clear guide to the Kahn and DFS approaches, when multiple valid orders exist, and why the graph must be acyclic first.","keywords":["topological sort 2026","topological sort algorithm","kahn algorithm explained","topological sort dag","topological order graph","dfs topological sort","topological sort python","dependency resolution algorithm","graph sorting algorithm"],"tldr":["**It only works on a DAG** — feed it a graph with a cycle and there is no valid order to find, by definition.","**The output is an ordering, not a single correct answer** — most DAGs have several valid topological orders, and that is expected behavior.","**Two algorithms dominate** — the Kahn approach (repeatedly remove nodes with no remaining incoming edges) and DFS-based sort walk the graph differently but reach an equally valid order.","**It is how \"run in dependency order\" gets implemented** — build systems, package installers, and task schedulers all lean on a topological sort under the hood.","**Skip:** trying to sort a graph you have not validated as acyclic first — build the cycle check into the pipeline itself, not as an afterthought."],"readTime":"4 min read","wordCount":812},"related":[{"slug":"what-is-a-directed-acyclic-graph-2026","title":"What Is a Directed Acyclic Graph? 2026 Guide","excerpt":"A directed acyclic graph, or DAG, is a graph whose edges point one way and never loop back on themselves. Here is what that one rule enables and where DAGs quietly run your software.","category":"code","date":"July 17, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":240},{"slug":"what-is-a-higher-order-function-2026","title":"What Is a Higher-Order Function? 2026 Guide","excerpt":"A higher-order function takes a function as an argument, returns one, or both. Here is why that one capability underpins map, filter, reduce, and most functional-style code.","category":"code","date":"July 18, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":200},{"slug":"quicksort-vs-mergesort-2026","title":"Quicksort vs Mergesort in 2026: How to Choose","excerpt":"Quicksort and mergesort both run in O(n log n) on average but make different tradeoffs on memory, stability, and worst-case behavior. Here is how to pick.","category":"code","date":"July 16, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":150}],"sameCategory":[{"slug":"bazel-build-explained-2026","title":"Bazel Explained: What Hermetic Builds Actually Cost","excerpt":"Bazel delivers reproducible, precisely cached builds and demands that you describe everything. Here is what you get, what it costs, and who should say no.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":145},{"slug":"graphql-federation-2026","title":"GraphQL Federation: One Graph, Many Teams","excerpt":"Federation composes independently-owned subgraphs into a single API. Here is what it solves, the operational cost it adds, and when a simpler gateway is enough.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":300},{"slug":"hermetic-builds-explained-2026","title":"Hermetic Builds Explained: Same Inputs, Same Output","excerpt":"A hermetic build depends only on declared inputs. Here is what that property gives you, the common leaks that break it, and how to move toward it incrementally.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":130},{"slug":"monorepo-tooling-compared-2026","title":"Monorepo Tooling Compared: What You Actually Need","excerpt":"Monorepo tools solve task orchestration and caching, not repository layout. Here is what each tier provides and how to tell when you have outgrown the simple option.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":150}],"newer":{"slug":"what-is-tokenization-in-llms-2026","title":"What Is Tokenization in LLMs in 2026? Full Explainer","excerpt":"Before a language model reads anything, tokenization breaks text into the subword units it actually operates on. Here is how that process works and why it matters.","category":"ai","date":"July 24, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":200},"older":{"slug":"what-is-transformer-architecture-2026","title":"What Is Transformer Architecture in 2026? Full Breakdown","excerpt":"The transformer is the architecture behind nearly every modern language model. Here is a practitioner-level breakdown of its parts and why each one exists.","category":"ai","date":"July 24, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":240}}