Browse curriculum

Graphs (Topological Sort)

The Graphs (Topological Sort) Pattern

Topological sort orders the nodes of a directed acyclic graph so every edge points forward. It is produced either by repeatedly removing nodes with no remaining prerequisites (Kahn’s algorithm) or by reversing a DFS finish order.

3

Interactive problems

1

Free to open

Recognise

How do you recognise a graphs (topological sort) problem?

Tasks have prerequisites and you need a valid order, or you need to detect whether the dependencies contain a cycle. Course schedules, build orders and dependency resolution are all this.

Complexity

What is the time complexity of the graphs (topological sort) pattern?

O(V + E). If the algorithm finishes having emitted fewer than V nodes, the graph contains a cycle — which is how cycle detection falls out for free.

Problems

Graphs (Topological Sort) practice problems

Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.

Complexity

Graphs (Topological Sort) problems by difficulty and complexity

The difficulty, running time and extra space of every graphs (topological sort) solution on this page, as each lesson derives them.

LessonDifficultyBestAverageWorstSpace
Ordering Dependencies (Topological Sort)MediumΩ(V + E)Θ(V + E)O(V + E)O(V + E)
Course ScheduleMediumΩ(V + E)Θ(V + E)O(V + E)O(V + E)
Course Schedule IIMediumΩ(V + E)Θ(V + E)O(V + E)O(V + E)
Curriculum

The underlying technique is covered from first principles in the graphs (topological sort) lesson in the DSA visualizer curriculum. Graphs (Topological Sort) is one of the 17 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern