Chaturmind
LearnDSASystem DesignBlogPremium
Sign inGet started
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML

Company

  • Blog
  • Premium
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Trees & Graphs

Binary Trees

  • Tree Traversal (DFS & BFS)
  • Binary Search Tree Operations

Graph Algorithms

  • Graph DFS & BFS
  • Topological Sort
  • Union-Find (Disjoint Sets)
Chaturmind
← Trees & Graphs

Binary Trees

  • Tree Traversal (DFS & BFS)
  • Binary Search Tree Operations

Graph Algorithms

  • Graph DFS & BFS
  • Topological Sort
  • Union-Find (Disjoint Sets)
HomeLearnDSATrees, Graphs & Advanced DSAGraph Algorithms
✓ FreeAdvanced· 13 min read

Topological Sort

Implement topological ordering with DFS and Kahn's BFS algorithm for dependency resolution.

Published March 13, 2025


Topological Sort

Topological sort orders the vertices of a Directed Acyclic Graph (DAG) so that for every edge u → v, vertex u comes before v. It's used for dependency resolution: build systems, course prerequisites, task scheduling.

Kahn's Algorithm (BFS / In-degree)

public int[] topologicalSort(int n, int[][] prerequisites) {
    List<List<Integer>> adj = new ArrayList<>();
    int[] inDegree = new int[n];
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());

    for (int[] pre : prerequisites) {
        adj.get(pre[1]).add(pre[0]); // pre[1] must come before pre[0]
        inDegree[pre[0]]++;
    }

    Queue<Integer> queue = new LinkedList<>();
    for (int i = 0; i < n; i++)
        if (inDegree[i] == 0) queue.offer(i); // start with nodes with no deps

    int[] order = new int[n];
    int idx = 0;
    while (!queue.isEmpty()) {
        int node = queue.poll();
        order[idx++] = node;
        for (int neighbor : adj.get(node)) {
            if (--inDegree[neighbor] == 0) queue.offer(neighbor);
        }
    }

    return idx == n ? order : new int[0]; // empty if cycle detected
}

Course Schedule — can you complete all courses?

// LeetCode 207
public boolean canFinish(int numCourses, int[][] prerequisites) {
    List<List<Integer>> adj = new ArrayList<>();
    int[] inDegree = new int[numCourses];
    for (int i = 0; i < numCourses; i++) adj.add(new ArrayList<>());
    for (int[] pre : prerequisites) {
        adj.get(pre[1]).add(pre[0]);
        inDegree[pre[0]]++;
    }
    Queue<Integer> queue = new LinkedList<>();
    for (int i = 0; i < numCourses; i++)
        if (inDegree[i] == 0) queue.offer(i);
    int completed = 0;
    while (!queue.isEmpty()) {
        int course = queue.poll();
        completed++;
        for (int next : adj.get(course))
            if (--inDegree[next] == 0) queue.offer(next);
    }
    return completed == numCourses;
}

DFS-Based Topological Sort

public List<Integer> topologicalSortDFS(int n, List<List<Integer>> adj) {
    boolean[] visited = new boolean[n];
    boolean[] inStack = new boolean[n];
    Deque<Integer> stack = new ArrayDeque<>();
    boolean[] hasCycle = {false};

    for (int i = 0; i < n; i++)
        if (!visited[i]) dfs(adj, i, visited, inStack, stack, hasCycle);

    if (hasCycle[0]) return Collections.emptyList();
    List<Integer> result = new ArrayList<>();
    while (!stack.isEmpty()) result.add(stack.pop());
    return result;
}

void dfs(List<List<Integer>> adj, int node, boolean[] visited,
         boolean[] inStack, Deque<Integer> stack, boolean[] hasCycle) {
    visited[node] = true;
    inStack[node] = true;
    for (int neighbor : adj.get(node)) {
        if (!visited[neighbor]) dfs(adj, neighbor, visited, inStack, stack, hasCycle);
        else if (inStack[neighbor]) hasCycle[0] = true;
    }
    inStack[node] = false;
    stack.push(node); // add to result AFTER processing all neighbors
}

Alien Dictionary — derive character order

// Given sorted alien words, find the character ordering
// Build a graph: if words[i][j] != words[i+1][j], then words[i][j] comes before words[i+1][j]
// Then topological sort the character graph

Complexity

  • Time: O(V + E) where V = vertices, E = edges
  • Space: O(V + E) for adjacency list

Interview Tips

  1. Cycle detection: if Kahn's algorithm doesn't process all nodes, there's a cycle — the graph isn't a DAG.
  2. When to use Kahn's vs DFS: Kahn's is easier to implement iteratively; DFS is more natural recursively. Both are valid.
  3. Real-world: Maven/Gradle build dependency resolution uses topological sort.

Previous

Graph DFS & BFS

Next

Union-Find (Disjoint Sets)

AI Tutor

Lesson: Topological Sort

Quick actions

AI responses can be inaccurate. Verify critical information.