V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Topological Sort

Kahn's algorithm for ordering dependencies in a DAG

Turn a partial order into a valid sequence

In a directed dependency graph, edge u -> v means that u must appear before v. A topological order satisfies every such edge. It exists only when the graph is acyclic.

Remove vertices with no remaining prerequisite

Kahn's algorithm counts every vertex's indegree. Any vertex with indegree 0 is ready to output. Removing it deletes its outgoing edges, which may reduce another vertex to indegree 0. The player shows indegrees as node badges, the active ready vertex in amber, and completed vertices in green.

A1B2C0D1E0F3

Count the incoming edges of every vertex.

1function topoSort(edges: [number, number][], n: number): number[] {
2 const indeg = Array(n).fill(0);
3 for (const [u, v] of edges) indeg[v]++;
4 const order: number[] = [];
5 const done = Array(n).fill(false);
6 while (order.length < n) {
7 let u = -1;
8 for (let i = 0; i < n; i++)
9 if (!done[i] && indeg[i] === 0) { u = i; break; }
10 if (u === -1) break;
11 done[u] = true;
12 order.push(u);
13 for (const [a, b] of edges) if (a === u) indeg[b]--;
14 }
15 return order;
16}
Current vertex-
Output-
Remaining6
indegree[A]1
indegree[B]2
indegree[C]0
indegree[D]1
indegree[E]0
indegree[F]3
1 / 14

Cycles and non-unique answers

Several vertices may be ready at once, so a DAG can have many valid orders. This demonstration chooses the lowest-index ready vertex for a deterministic trace. If vertices remain but none has indegree 0, those dependencies contain a directed cycle. Processing each vertex and edge once takes O(V + E) time.

Typical uses include build scheduling, course prerequisites, spreadsheet recalculation, and detecting circular dependencies.

Continue the graph path with Dijkstra's shortest-path invariant.