How to sort depended objects by dependency
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Sorting objects by their dependencies so that every object appears after the objects it depends on is called topological sorting. This is used in build systems (compile dependencies before dependents), package managers (install prerequisites first), task schedulers (run prerequisite tasks first), and spreadsheet formula evaluation. A valid topological order exists only when the dependency graph has no cycles.
Modeling Dependencies as a Graph
Represent each object as a node and each dependency as a directed edge from prerequisite to dependent.
This means A must come before B, both A and B must come before C, and C must come before D. A valid order is [A, B, C, D].
Kahn's Algorithm (BFS)
Kahn's algorithm processes nodes with zero incoming edges first, then removes their outgoing edges. This naturally produces a topological order.
If the result contains fewer nodes than the input, a cycle exists and no valid topological order is possible.
DFS-Based Topological Sort
A depth-first search approach marks nodes as visited and appends them to the result in post-order (after all descendants are processed), then reverses the result.
The in_progress set detects cycles by catching back-edges during traversal.
Comparison
| Approach | Time | Space | Cycle detection | Output order |
| Kahn's (BFS) | O(V + E) | O(V + E) | By result size | Deterministic with sorted queue |
| DFS | O(V + E) | O(V + E) | By back-edge detection | Depends on iteration order |
Both algorithms have the same time complexity. Kahn's is often preferred when you want a deterministic order (use a priority queue instead of a deque). DFS is more natural when the graph is already represented with adjacency lists.
Using Python's graphlib (3.9+)
Python 3.9 added graphlib.TopologicalSorter to the standard library.
TopologicalSorter also supports incremental processing with prepare(), get_ready(), and done() for parallel task execution.
Real-World Applications
Build systems: Makefiles and CMake compute build order by topological sort of source file dependencies.
Package managers: pip, npm, and apt resolve install order by topological sort of package dependency trees.
Spreadsheet formulas: Cells that reference other cells must be evaluated after their dependencies. Circular references are detected as cycles.
Common Pitfalls
- Not detecting cycles — an infinite loop or incorrect results occur if the graph contains circular dependencies. Always check for cycles explicitly.
- Assuming a unique topological order — multiple valid orderings usually exist. If determinism matters, sort candidates at each step (alphabetically or by priority).
- Confusing dependency direction — "A depends on B" means B must come first, so the edge goes from B to A in the adjacency list.
- Forgetting isolated nodes — nodes with no dependencies and no dependents still need to appear in the output.
- Using recursion on very deep dependency chains — DFS can hit Python's recursion limit. Use
sys.setrecursionlimit()or switch to iterative DFS for deep graphs.
Summary
- Topological sorting orders objects so that dependencies come before dependents.
- Kahn's algorithm (BFS) removes zero-in-degree nodes iteratively; DFS appends nodes in post-order.
- Both run in O(V + E) time and detect cycles.
- Python 3.9+ provides
graphlib.TopologicalSorterin the standard library. - Always validate that the graph is acyclic before assuming a valid order exists.
Related reading
- How to sort faster than n log n given a strong condition on the list?
- How to sort in-place using the merge sort algorithm?
- How to sort List of objects by some property
- How to sort ListFile to list directories first and grouping files by directory?
- How to sort one list based on another?
- How to sort two arrays with one being sorted based on the sorting of the other?
- How to sort mongodb with pymongo
- How to sort pandas dataframe by one column

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 courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.