Topological Sort
topological-sort
Algorithms
Graph Algorithms (Core)
Webpack figures out the order to compile your modules using topological sort. Google Maps figures out the route to your destination using Dijkstra. Your CI system rejects circular imports using cycle detection. The same handful of graph algorithms power an enormous slice of real infrastructure, and almost all of them are short additions to a BFS or DFS skeleton you already wrote. **Graph Algorithms (Core)** covers that handful in detail. You will implement topological sort in two ways (Kahn's BFS-with-in-degree algorithm and the DFS-reverse-postorder algorithm), cycle detection on undirected graphs (DFS with parent tracking) and on directed graphs (DFS with white/gray/black coloring), Dijkstra's shortest-path algorithm with a min-heap and the relaxation invariant that makes it work, connected-component counting via DFS or Union-Find, and bipartite checking via two-color BFS. Along the way you will see why Dijkstra fails on negative edge weights, which motivates Bellman-Ford in the advanced lesson later. In **BFS & DFS (Intro)**, you wrote the two traversal skeletons. **Weighted Graph Representation** gave you the adjacency-list-of-tuples format that Dijkstra and friends actually consume. This lesson is where those primitives turn into named algorithms with clear use cases. From here, **Greedy (Intro)** introduces a different paradigm: instead of exploring every option, commit to the locally best choice at each step.
Not Started
0%
Practice Problems
Alien Dictionary
Given a sorted list of words in an alien language, determine the order of characters in the alien alphabet using topological sort.
Course Schedule II
Given courses and prerequisites, return a valid order to take all courses (topological ordering), or an empty array if impossible.
Course Schedule
Given a number of courses and their prerequisites, determine if it is possible to finish all courses (detect if the dependency graph has a cycle).
Minimum Height Trees
Given a tree of n nodes, find all roots that would minimize the tree's height when the tree is rooted at them.
Code Snippets
Topological Sort (Kahn's Algorithm)
Topological sort orders the nodes of a DAG so that every edge points from earlier to later. It is the algorithm behind build-system dependency resolution, course-prerequisite scheduling, and pipelined computation. This snippet covers Kahn's BFS-based algorithm with indegree tracking, a DFS-based variant that produces the same order via post-order, and a cycle-detection variant that returns null when the graph is not acyclic.
