Interview's MateDSA Visualizer
Interview's Mate

DSA Visualizer

Learn by watching algorithms run

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
All topics
PROBLEM-SOLVING TECHNIQUES

Topological Sorting

Order tasks so every dependency comes before the task that needs it.

Advanced6 problems2 interactive subtopicsO(V + E) time · O(V + E) space
Practice in AI DSA
WalkthroughOverviewRecognize itMistakes & edge casesKnowledge check (3)Practice
Algorithms & custom examples (2)Open in full playground →
STEP 1/5Count prerequisites
only course 0 has no prerequisites
order
0
1
2
3
in 0in 1in 1in 2
QUEUE
0
  • waiting / queued
  • active this step
  • result
Space Play←→ StepR Replay
1 / 5
PYTHONn = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]
1from collections import deque
2
3def find_order(n, prerequisites):
4 graph = [[] for _ in range(n)]
5 indegree = [0] * n
6 for course, pre in prerequisites:
7 graph[pre].append(course)
8 indegree[course] += 1
▶9 queue = deque(i for i in range(n) if indegree[i] == 0)
10 order = []
11 while queue:
12 node = queue.popleft()
13 order.append(node)
14 for nxt in graph[node]:
15 indegree[nxt] -= 1
16 if indegree[nxt] == 0:
17 queue.append(nxt)
18 return order if len(order) == n else []
STEP 1 OF 5Setup

Count prerequisites

0 needs nothing, 1 and 2 need one course each, 3 needs two. Only 0 can start.

VARIABLES

indegree
[0, 1, 1, 2]
queue
[0]
order
[]
02

Intuition & complexity

The core mental model, trade-offs, and Big-O cost.

What it is

A topological order lists the nodes of a directed acyclic graph so every edge points forward. Kahn’s algorithm repeatedly takes a node with no remaining prerequisites.

Why it matters

Build systems, course schedules and pipelines all need a valid order - and need to detect when none exists because of a cycle.

Think of it like this

Getting dressed: socks before shoes, shirt before jacket - any order that respects those rules works.

Use it when

  • Prerequisites or dependencies
  • Detecting cycles in a directed graph
  • DP over a directed acyclic graph

Avoid it when

  • Undirected graphs
  • Graphs with a cycle when you need a complete order - none exists

Complexity cheatsheet

OperationTimeSpace
Kahn’s algorithmO(V + E)O(V + E)
DFS-based orderingO(V + E)O(V + E)
Cycle check via order lengthO(V + E)-

Often confused with: plain BFS - it explores distance; Kahn’s algorithm uses in-degrees on a directed graph.

03

How to recognize it

Clues in interview prompts that point straight to this pattern.

prerequisitescourse scheduledependenciesbuild orderalien dictionary
  • If the output has fewer than n nodes, there is a cycle
  • Several valid orders can exist - ask whether any one is accepted
04

Mistakes & edge cases

Catch common off-by-one bugs and corner cases before submitting.

Common mistakes

  • Reversing the edge direction (pre to course vs course to pre)
  • Forgetting nodes that have no edges at all
  • Returning a partial order instead of reporting the cycle

Edge cases to test

  • No prerequisites - any order works
  • A cycle like [[0, 1], [1, 0]] - return []
  • A course that depends on itself
Interview tip: State the edge direction before coding - it’s the most common bug.
05

Knowledge check

Quick check to lock in the intuition.

Question 1 of 3

Kahn’s algorithm outputs only 3 of 4 nodes. What does that mean?

06

Practice

Apply what you just watched on real interview problems.

Generate Graph Theory problem in AI DSA Practice →
  • BeginnerCourse ScheduleLeetCode 207 ↗ (opens in a new tab)
  • IntermediateCourse Schedule IILeetCode 210 ↗ (opens in a new tab)
  • AdvancedBuild a Matrix With ConditionsLeetCode 2392 ↗ (opens in a new tab)
Depth-First SearchUnion Find