Graph Algorithms

Topological Sort: Kahn's Algorithm

An essential algorithm for ordering tasks with dependencies, Kahn's algorithm provides an intuitive, queue-based approach to sorting Directed Acyclic Graphs (DAGs).

Kahn's Algorithm in Python

Here is a Python implementation of Kahn's algorithm for topological sorting.

from collections import deque

def topological_sort_kahn(graph):
    in_degree = {u: 0 for u in graph}
    for u in graph:
        for v in graph[u]:
            in_degree[v] += 1

    queue = deque([u for u in in_degree if in_degree[u] == 0])
    top_order = []

    while queue:
        u = queue.popleft()
        top_order.append(u)

        for v in graph[u]:
            in_degree[v] -= 1
            if in_degree[v] == 0:
                queue.append(v)

    if len(top_order) == len(graph):
        return top_order
    else:
        return []  # Graph has a cycle

AI Coach Hint: Kahn's algorithm is not just for sorting; it's also a great way to detect cycles in a graph. If the number of nodes in the topological order is not equal to the total number of nodes in the graph, it means there's at least one cycle.

Related Algorithm Guides

Explore more algorithm interview guides powered by AI coaching

Heap Vs Bst Interview Questions
AI-powered interview preparation guide
Topological Sort Interview Questions
AI-powered interview preparation guide
Graph Traversal Algorithms Interview Questions
AI-powered interview preparation guide
Github Copilot Alternative Interview Ai
AI-powered interview preparation guide