Graph Algorithms

Topological Sort: DFS Approach

A powerful, recursive method for ordering tasks in a Directed Acyclic Graph (DAG), the DFS-based topological sort is a cornerstone of graph theory interviews.

DFS Topological Sort in Python

Here is a Python implementation of topological sorting using Depth-First Search.

def topological_sort_dfs(graph):
    visited = set()
    recursion_stack = set()
    result = []

    def dfs(u):
        visited.add(u)
        recursion_stack.add(u)

        for v in graph.get(u, []):
            if v not in visited:
                if not dfs(v):
                    return False
            elif v in recursion_stack:
                return False  # Cycle detected

        recursion_stack.remove(u)
        result.insert(0, u)
        return True

    for u in list(graph):
        if u not in visited:
            if not dfs(u):
                return []  # Cycle detected

    return result

AI Coach Hint: The key to the DFS-based topological sort is adding the vertex to the *front* of the result list *after* visiting all its neighbors. This ensures that a vertex appears before all vertices it has edges to.

Related Algorithm Guides

Explore more algorithm interview guides powered by AI coaching

Bellman Ford Algorithm Interview Questions
AI-powered interview preparation guide
Floyd Warshall Algorithm Interview Questions
AI-powered interview preparation guide
Embedded Systems Engineer Interview Questions
AI-powered interview preparation guide
Public Speaking Experience Interview Preparation
AI-powered interview preparation guide