Topological Sort (Kahn's & DFS)
Trees & GraphsLinear dependency ordering and cycle detection in Directed Acyclic Graphs (DAG)
39 problems·1 Easy·15 Medium·23 Hard
Pattern Study Guide & Cheat Sheet▼
Linearly order vertices in a Directed Acyclic Graph (DAG) such that for every directed edge u -> v, vertex u comes before v (Kahn's algorithm using indegree BFS).
Core Invariant: Kahn's Algorithm: Any node with `indegree == 0` has no remaining prerequisites and can be processed immediately. When processed, decrement indegrees of all outgoing neighbors; new 0-indegree nodes become eligible.
Recognize it (Keywords & Signals)
- Task prerequisite scheduling / course schedule
- Compilation dependency order
- Build system build sequence
- Detect cycle in directed graph
- Alien dictionary (derive alphabet ordering)
When NOT to use
Undirected graphs (use standard BFS/DFS or DSU) or graphs known to contain self-loops/cycles where no order can exist.
How to solve (Step-by-step)
- 1.Build adjacency list `graph` and calculate `indegree` array/map for all nodes.
- 2.Enqueue all nodes with `indegree == 0` into a `queue`.
- 3.Initialize `order = []`.
- 4.While queue: pop `curr`, append to `order`. For each neighbor `nxt` of `curr`, decrement `indegree[nxt] -= 1`.
- 5.If `indegree[nxt] == 0`, enqueue `nxt`.
- 6.Cycle check: if `len(order) == num_nodes`, a valid topological order exists; otherwise, a directed cycle was present!
Watch for (Interview Traps)
- Reversing edge directions (e.g. `[a, b]` direction is `b -> a`, not `a -> b`)
- Failing to detect cycles by assuming all nodes are processed
- Disconnected nodes: ensure all vertices `0..n-1` are registered in the indegree table
Kahn's Algorithm (BFS Indegree Topological Sort)
from collections import deque, defaultdict
def topological_sort(num_courses: int, prerequisites: list[list[int]]) -> list[int]:
graph = defaultdict(list)
indegrees = [0] * num_courses
# Prerequisite [a, b] means: must take b before a (edge: b -> a)
for course, prereq in prerequisites:
graph[prereq].append(course)
indegrees[course] += 1
# Start with all nodes having zero prerequisites
queue = deque([i for i in range(num_courses) if indegrees[i] == 0])
order = []
while queue:
curr = queue.popleft()
order.append(curr)
for next_course in graph[curr]:
indegrees[next_course] -= 1
if indegrees[next_course] == 0:
queue.append(next_course)
# If order doesn't include all courses, a cycle exists
return order if len(order) == num_courses else []- Cost
- O(V + E) linear scan of nodes and dependency edges · O(V + E) graph + queue (Optimal linear time dependency resolution.)
Canonical problems
#207 Course Schedule: Detect if prerequisites form a cycle (len(order) == n)
#210 Course Schedule II: Return the actual linear order of courses
#269 Alien Dictionary: Derive character edge directions from adjacent words and sort
#310 Minimum Height Trees: Repeatedly trim leaves (degree 1) inward toward the center
⌘K
Hard·20 companies·Max freq 93%·Acc 56.8%
DoorDashWeRideDuolingo+17
Medium·10 companies·Max freq 92%·Acc 57.0%
VerilyZeta GlobalDocusign+7
Hard·6 companies·Max freq 100%·Acc 0.5%
Hudson River TradingHudson River TradingTarget+3
Hard·5 companies·Max freq 60%·Acc 61.8%
NutanixMicrosoftOracle+2
Hard·5 companies·Max freq 56%·Acc 57.2%
JuspayLinkedInGoogle+2
Hard·5 companies·Max freq 56%·Acc 66.0%
CitadelMetaAmazon+2
Medium·5 companies·Max freq 25%·Acc 37.6%
MetaAmazonGoogle+2
Medium·4 companies·Max freq 63%·Acc 62.3%
OracleGoogleAmazon+1
Medium·1 companies·Max freq 25%·Acc 41.5%
Google
# | Problem | Difficulty | Top Companies↓ | Frequency | Acceptance | |
|---|---|---|---|---|---|---|
| #207 | Course Schedule Depth-First SearchBreadth-First SearchGraph TheoryTopological SortDirected Acyclic Graph | Medium | 100% | 51.8% | ||
| #210 | Course Schedule II Depth-First SearchBreadth-First SearchGraph TheoryTopological Sort | Medium | 100% | 55.9% | ||
| #269 | Alien Dictionary ArrayStringDepth-First SearchBreadth-First SearchGraph TheoryTopological SortDirected Acyclic Graph | Hard | 100% | 37.3% | ||
| #329 | Longest Increasing Path in a Matrix ArrayDynamic ProgrammingDepth-First SearchBreadth-First SearchGraph TheoryTopological SortMemoizationMatrixDirected Acyclic Graph | Hard | 93% | 56.8% | ||
| #2603 | Collect Coins in a Tree ArrayTreeGraph TheoryTopological Sort | Hard | 100% | 39.5% | ||
| #2050 | Parallel Courses III ArrayDynamic ProgrammingGraph TheoryTopological SortDirected Acyclic Graph | Hard | 100% | 66.8% | ||
| #2115 | Find All Possible Recipes from Given Supplies ArrayHash TableStringGraph TheoryTopological SortDirected Acyclic Graph | Medium | 92% | 57.0% | ||
| #631 | Design Excel Sum Formula ArrayHash TableStringGraph TheoryDesignTopological SortMatrix | Hard | 100% | 39.6% | ||
| #953 | Verifying an Alien Dictionary ArrayHash TableString | Easy | 88% | 56.0% | ||
| #310 | Minimum Height Trees Depth-First SearchBreadth-First SearchGraph TheoryTopological Sort | Medium | 100% | 42.6% | ||
| #2360 | Longest Cycle in a Graph Depth-First SearchBreadth-First SearchGraph TheoryTopological SortKosaraju's AlgorithmTarjan's SCC Algorithm | Hard | 88% | 50.9% | ||
| #1136 | Parallel Courses Graph TheoryTopological SortDirected Acyclic Graph | Medium | 81% | 62.3% | ||
| #851 | Loud and Rich ArrayDepth-First SearchGraph TheoryTopological SortDirected Acyclic Graph | Medium | 65% | 63.8% | ||
| #802 | Find Eventual Safe States Depth-First SearchBreadth-First SearchGraph TheoryTopological SortKosaraju's AlgorithmTarjan's SCC Algorithm | Medium | 50% | 71.2% | ||
| #1245 | Tree Diameter TreeDepth-First SearchBreadth-First SearchGraph TheoryTopological SortDP on Trees | Medium | 39% | 61.3% | ||
| #630 | Course Schedule III ArrayGreedySortingHeap (Priority Queue) | Hard | 100% | 41.9% | ||
| #2246 | Longest Path With Different Adjacent Characters ArrayStringTreeDepth-First SearchGraph TheoryTopological Sort | Hard | 100% | 0.5% | ||
| #1462 | Course Schedule IV Depth-First SearchBreadth-First SearchGraph TheoryTopological Sort | Medium | 50% | 60.0% | ||
| #2127 | Maximum Employees to Be Invited to a Meeting ArrayDynamic ProgrammingDepth-First SearchGraph TheoryTopological SortKosaraju's AlgorithmTarjan's SCC Algorithm | Hard | 60% | 61.8% | ||
| #1857 | Largest Color Value in a Directed Graph Hash TableStringDynamic ProgrammingGraph TheoryTopological SortMemoizationCountingDirected Acyclic Graph | Hard | 56% | 57.2% | ||
| #1203 | Sort Items by Groups Respecting Dependencies Depth-First SearchBreadth-First SearchGraph TheoryTopological SortDirected Acyclic Graph | Hard | 56% | 66.0% | ||
| #1976 | Number of Ways to Arrive at Destination Dynamic ProgrammingGraph TheoryTopological SortShortest PathDijkstra's Algorithm | Medium | 25% | 37.6% | ||
| #2192 | All Ancestors of a Node in a Directed Acyclic Graph Depth-First SearchBreadth-First SearchGraph TheoryTopological SortDirected Acyclic Graph | Medium | 63% | 62.3% | ||
| #1632 | Rank Transform of a Matrix ArrayUnion-FindGraph TheoryTopological SortSortingMatrix | Hard | 56% | 42.4% | ||
| #2328 | Number of Increasing Paths in a Grid ArrayDynamic ProgrammingDepth-First SearchBreadth-First SearchGraph TheoryTopological SortMemoizationMatrix | Hard | 88% | 57.3% | ||
| #2204 | Distance to a Cycle in Undirected Graph Depth-First SearchBreadth-First SearchGraph TheoryTopological Sort | Hard | 38% | 73.9% | ||
| #444 | Sequence Reconstruction ArrayGraph TheoryTopological SortDirected Acyclic Graph | Medium | 38% | 31.0% | ||
| #3620 | Network Recovery Pathways ArrayBinary SearchDynamic ProgrammingGraph TheoryTopological SortHeap (Priority Queue)Shortest Path | Hard | 13% | 50.9% | ||
| #2876 | Count Visited Nodes in a Directed Graph Dynamic ProgrammingDepth-First SearchGraph TheoryTopological SortMemoizationKosaraju's AlgorithmTarjan's SCC Algorithm | Hard | 100% | 31.1% | ||
| #3435 | Frequencies of Shortest Supersequences ArrayStringBit ManipulationGraph TheoryTopological SortEnumeration | Hard | 100% | 22.8% | ||
| #1916 | Count Ways to Build Rooms in an Ant Colony ArrayMathDynamic ProgrammingTreeDepth-First SearchGraph TheoryTopological SortCombinatoricsDP on TreesFermat's Little Theorem | Hard | 88% | 51.8% | ||
| #3383 | Minimum Runes to Add to Cast Spell ArrayDepth-First SearchBreadth-First SearchGraph TheoryTopological Sort | Hard | 75% | 44.7% | ||
| #3481 | Apply Substitutions ArrayHash TableStringDepth-First SearchBreadth-First SearchGraph TheoryTopological Sort | Medium | 43% | 77.9% | ||
| #1728 | Cat and Mouse II ArrayMathDynamic ProgrammingGraph TheoryTopological SortMemoizationMinimaxMatrixGame TheoryZero-Sum Game | Hard | 25% | 40.4% | ||
| #1786 | Number of Restricted Paths From First to Last Node Dynamic ProgrammingGraph TheoryTopological SortHeap (Priority Queue)Shortest PathDijkstra's Algorithm | Medium | 25% | 41.5% | ||
| #2392 | Build a Matrix With Conditions ArrayGraph TheoryTopological SortMatrixDirected Acyclic Graph | Hard | 25% | 79.3% | ||
| #1059 | All Paths from Source Lead to Destination Graph TheoryTopological SortKosaraju's AlgorithmTarjan's SCC Algorithm | Medium | 25% | 37.3% | ||
| #1591 | Strange Printer II ArrayGraph TheoryTopological SortMatrixDirected Acyclic Graph | Hard | 25% | 61.1% | ||
| #2371 | Minimize Maximum Value in a Grid ArrayUnion-FindGraph TheoryTopological SortSortingMatrix | Hard | 25% | 70.1% |
Showing 39 of 39 problems in Topological Sort (Kahn's & DFS)Filtered: All Companies