Topological sort in OCaml
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.
Introduction
Topological sort gives a valid order for tasks that depend on earlier tasks in a directed acyclic graph. In OCaml, this problem is a good example of balancing immutable data with practical algorithmic performance. A clean implementation should produce the ordering, and it should also tell you when the input graph contains a cycle.
Model the Graph in OCaml
A practical representation is an adjacency map keyed by vertex name. This keeps lookups fast and still fits a functional style. The code below builds a graph from edge pairs while making sure every vertex exists as a key, even when it has no outgoing edges.
This format is simple to inspect and easy to transform. It also makes it straightforward to compute in degree counts for Kahn style sorting.
Implement Kahn Topological Sort
Kahn algorithm repeatedly removes vertices with in degree zero. Each removed vertex is appended to the result, and its outgoing edges are deleted by decrementing in degree for neighbors. If some vertices remain after processing, the graph had at least one cycle.
Related reading
- Topological sort of cyclic graph with minimum number of violated edges
- Topological sort to find the number of paths to t
- Topological sort using DFS without recursion
- Topological sorting in PHP
- Tornado generator resume on any future in list
- TPR FPR Curve for different classifiers - kNN, NaiveBayes, Decision Trees in R
- Topology-matching algorithm for finding 2D lattice in a 3D lattice
- Tournament bracket placement algorithm

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.