Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Graphs

Topological Sort

O(V + E)

Repeatedly take nodes with in-degree 0 (Kahn's), or DFS and emit on the way out; a cycle means no ordering.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
Learn firstGraph BFS / DFSUnlocksGames on Graphs (retrograde analysis)Dominator Tree
0%
mastery
0/19 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

Prerequisites, dependencies, build order on a DAG; cycle detection in a directed graph; DP over a DAG; order from comparisons (alien dictionary).

  1. 1Brute force

    Repeatedly scan for a vertex with no incoming edges: O(V2).

  2. 2The observation

    Rescanning: maintain in-degrees and a queue of zero-in-degree vertices.

  3. 3Why it works

    Every vertex output so far has all its predecessors output before it.

Reach for it when

  • +Dependencies / prerequisites / build order on a directed graph; produce a valid linear order.
  • +'Can you finish' / detect a cycle in a directed graph (count outputs vs n).
  • +Layered processing where nodes free up as their prerequisites complete.

Not when

  • ×Graph is undirected (connectivity, cycles)use Union-find or plain DFS
  • ×You need shortest paths or distancesuse BFS / Dijkstra (topo order only helps DP on DAGs)
  • ×Graph has cycles that must be handled, not just reporteduse Condense SCCs first, then topo-sort the DAG
  • ×No dependency or direction at alluse You don't need an ordering

Intuition

Topological sort orders tasks so every prerequisite comes before the task that needs it. Course B needs Course A first → A must appear earlier in the list. It only makes sense on a DAG (directed graph, no cycles) — and if a cycle exists, no valid order is possible (you'd need A before B and B before A). That's why "Course Schedule: can you finish?" is really "is this graph acyclic?".

Read the full intuition

The clean method is Kahn's algorithm (BFS on in-degree):

  • in-degree of a node = how many prerequisites point into it.
  • Start every node with in-degree 0 in a queue (no prerequisites → can be taken now).
  • Pop one, add it to the order, and "remove" it: decrement each neighbour's in-degree; any neighbour that drops to 0 is now free → enqueue it.
  • If you manage to output all n nodes, it's a valid order. If fewer came out, the leftovers are tangled in a cycle.

Walk courses: 0→1, 0→2, 1→3, 2→3. In-degrees: [0,1,1,2]. Queue=[0]. Pop 0 → order [0], drop 1&2 to 0 → queue [1,2]. Pop 1 → [0,1], drop 3 to 1. Pop 2 → [0,1,2], drop 3 to 0 → queue [3]. Pop 3 → [0,1,2,3]. All 4 out → valid.

Key idea

The tells: "prerequisites", "dependencies", "build order", "can you finish", "valid ordering" on directed relationships. Counting how many you output is also your cycle detector — no extra work needed.

Why it costs what it costs

Time O(V + E). each node enqueued/dequeued once; each edge relaxes one in-degree once.

Space O(V + E). adjacency list plus in-degree array and queue.

Practice

Next · Foundation

Course Schedule

Kahn's algorithm: processed count < n means a cycle.

0/19 solved
  • Course ScheduleFoundationFoundationAmazon, UberMedium
  • Course Schedule IIApply it · Output an order.Apply itAmazon, UberMedium
  • Find Eventual Safe StatesOne change · Safe nodes cannot reach a cycle.One changeMedium
  • Alien DictionaryTwists · Edges must be inferred, with an invalid-prefix case.TwistsPremiumHard
  • Minimum Height TreesBranches · Undirected tree; peel leaves.BranchesGoogle, UberMedium
  • Longest Increasing Path in a MatrixCombine · DP on an implicit DAG.CombineGoogleHard
  • Longest Flight RouteCombine · Longest path in a DAG with reconstruction.CombineCSESMedium
  • Course Schedule IIAdvanced · Lexicographic constraint on the order.AdvancedCSESMedium
  • Sort Items by Groups Respecting DependenciesMastery checkMastery checkHard
  • Course ScheduleCSESMedium
  • Game RoutesCSESMedium
  • Reachable NodesCSESMedium

Pitfalls

Classic bugs

  • !Edge direction is prerequisite -> dependent; if [a,b] means b before a, flip it or you get a wrong/empty order.
  • !Cycle check: if len(order) < n in Kahn's, a cycle swallowed the rest; return failure.
  • !Enqueue all initial in-degree-0 nodes; there can be several disconnected starts.
  • !DFS variant needs 3 colours (white/gray/black) to catch back-edges; a plain visited set misses cycles.
  • !Lexicographically smallest order needs a min-heap, not a plain queue.
  • !Alien Dictionary: add an edge only from the first differing char; a longer word before its own prefix is invalid.

Looks like it, isn't

  • Parallel Courses II needs Bitmask DP
    Why
    Greedy picking of available courses per semester is wrong; n <= 15 invites DP over taken masks.
  • Count Ways to Build Rooms in an Ant Colony needs Combinatorics mod p (nCr, Catalan, stars and bars)
    Why
    Counting topological orders of a tree is n! / product of subtree sizes. No enumeration needed. source ↗
Go deepervariants and techniques · 8 combinations · resources

Variants and techniques

  • Strongly Connected Components & CondensationGroup vertices that reach each other (Tarjan or Kosaraju) and contract them into a DAG for further DP/topological reasoning.
  • Feasibility (cycle check)Run Kahn's; can finish ⟺ all n nodes output. Course Schedule.
  • Produce an orderReturn the dequeue sequence. Course Schedule II.
  • Peel leaves (undirected trees)Repeatedly remove degree-1 nodes layer by layer to find centroids. Minimum Height Trees.
  • Derive ordering from dataInfer edges from comparisons, then topo-sort the alphabet. Alien Dictionary.

Combinations

  • Topological Sort+1D / Fibonacci-style

    longest path / number of paths in a DAG; longest increasing path in a grid

    Topological Sort:
    provides an order where predecessors are final
    1D / Fibonacci-style:
    longest/count paths along that order

    Longest Flight RouteGame RoutesLongest Increasing Path in a Matrix

  • Strongly Connected Components & Condensation+Topological Sort+1D / Fibonacci-style

    maximum total collected on a walk in a directed graph with cycles

    Strongly Connected Components & Condensation:
    condenses cycles into super-nodes
    Topological Sort:
    orders the condensation DAG
    1D / Fibonacci-style:
    accumulates values along DAG paths

    Coin Collector

  • Strongly Connected Components & Condensation+2-SAT

    each item chooses one of two options with pairwise 'at least one' constraints

    Strongly Connected Components & Condensation:
    finds contradictions x <-> not x
    2-SAT:
    models the clauses as implications

    Giant Pizza

  • Topological Sort+Top-K Elements

    lexicographically smallest topological order; 'course 1 as early as possible'

    Topological Sort:
    dependency order
    Top-K Elements:
    priority among available vertices

    Course Schedule II

  • Bitset Optimisation+Topological Sort

    for every vertex of a DAG with n ~ 5e4, the number of vertices reachable from it

    Bitset Optimisation:
    reach[v] = {v} | OR of reach[child], 64 vertices per word
    Topological Sort:
    process vertices in reverse topological order

    Reachable Nodes

  • Strongly Connected Components & Condensation+Topological Sort+Bitset Optimisation

    many 'can a reach b' queries on a general directed graph with n ~ 5e4

    Strongly Connected Components & Condensation:
    condense cycles so reachability lives on a DAG
    Topological Sort:
    an order for the DP over components
    Bitset Optimisation:
    per-component reachability sets

    Reachability Queries

  • Games on Graphs (retrograde analysis)+Topological Sort+BFS/Dijkstra on an Augmented State Graph

    chase game on a graph or grid with possible draws

    Games on Graphs (retrograde analysis):
    labels propagate back from terminal states
    Topological Sort:
    Kahn-style degree counters decide LOSE once every move is known to lose
    BFS/Dijkstra on an Augmented State Graph:
    states are (mouse, cat, turn)

    Cat and MouseCat and Mouse II

  • Tree Hashing / Canonical Forms+Topological Sort

    are two unrooted trees isomorphic

    Tree Hashing / Canonical Forms:
    a canonical id of the tree rooted at each centre
    Topological Sort:
    leaf trimming finds the 1-2 centres of an unrooted tree

    Tree Isomorphism II

Resources

  • Graph Theory playlistWilliam Fiset · video
  • Graph TraversalUSACO Guide · course
  • Disjoint Set Unioncp-algorithms · article
  • Dijkstracp-algorithms · article
  • Topological sortingcp-algorithms · article
  • Shortest paths visualizerVisuAlgo · tool
  • Graph cheatsheetTech Interview Handbook · article
Graph BFS / DFSUnion-Find (Disjoint Set)
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial