Topological Sort

💡Strategies for Solving This Problem

Understanding Topological Sort

Topological sorting is a linear ordering of vertices in a directed acyclic graph (DAG) such that for every directed edge (u, v), vertex u comes before vertex v in the ordering. This is crucial for dependency resolution, task scheduling, and build systems.

When to Use Topological Sort

  • Course Prerequisites: Determine valid course ordering given prerequisites (LeetCode 207, 210)
  • Build Systems: Compile files in correct dependency order
  • Task Scheduling: Execute tasks respecting dependencies
  • Package Management: Install packages in correct order

Key Properties

  • Only works on Directed Acyclic Graphs (DAGs)
  • If graph has cycle, topological sort is impossible
  • Multiple valid orderings may exist
  • Can detect circular dependencies

Two Main Approaches

1. Kahn's Algorithm (BFS-based):

  • Start with nodes that have no incoming edges (in-degree = 0)
  • Remove node and its edges, add to result
  • Repeat with newly zero in-degree nodes
  • Time: O(V + E), Space: O(V)

2. DFS-based Approach:

  • Perform DFS from each unvisited node
  • Add node to result when all descendants visited (post-order)
  • Reverse result at end
  • Time: O(V + E), Space: O(V)

Cycle Detection

If we process fewer nodes than exist in graph, a cycle exists. Use visited states:

  • White: Unvisited
  • Gray: Currently processing (in recursion stack)
  • Black: Completely processed

If we encounter a gray node during DFS, we found a cycle.

Common Interview Questions

  • Course Schedule (LeetCode 207): Can you finish all courses?
  • Course Schedule II (LeetCode 210): Return valid course order
  • Alien Dictionary (LeetCode 269): Determine character ordering
  • Minimum Height Trees (LeetCode 310): Find tree roots

Asked at: Google, Facebook, Amazon, Microsoft, Uber

Scroll to Top