Browse curriculum

Graphs (Topological Sort)

Graph Interview Questions: 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. Below are the graph interview questions from LeetCode, each with a step-by-step visual solution.

16

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

Graph interview questions: 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)
Minimum Height TreesMediumΩ(n)Θ(n)O(n)O(n)
Alien DictionaryHardΩ(C)Θ(C)O(C)O(U + E)
Redundant ConnectionMediumΩ(n)Θ(n · α(n))O(n · α(n))O(n)
Accounts MergeMediumΩ(E log E)Θ(E log E)O(E log E)O(E)
Critical Connections in a NetworkHardΩ(V + E)Θ(V + E)O(V + E)O(V + E)
Keys and RoomsMediumΩ(rooms + keys)Θ(rooms + keys)O(rooms + keys)O(rooms)
Number of ProvincesMediumΩ(n²)Θ(n²)O(n²)O(n)
Reorder Routes to Make All Paths Lead to the City ZeroMediumΩ(n)Θ(n)O(n)O(n)
Evaluate DivisionMediumΩ(q + E)Θ(q · (V + E))O(q · (V + E))O(V + E)
Is Graph Bipartite?MediumΩ(V + E)Θ(V + E)O(V + E)O(V)
Number of Operations to Make Network ConnectedMediumΩ(1)Θ(n + E)O(n + E · α(n))O(n)
Path With Minimum EffortMediumΩ(1)Θ(R·C log(R·C))O(R·C log(R·C))O(R·C)
Reconstruct ItineraryHardΩ(E log E)Θ(E log E)O(E log E)O(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 18 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern