Data Structures & Algorithms

Topological Sort

Ace your coding interviews by mastering Topological Sort. Our guide provides in-depth explanations, classic problems, and AI-driven feedback to help you solve any dependency-based problem.

Topological Sort (Kahn's Algorithm)

Here is a Python implementation of Topological Sort using Kahn's algorithm, which uses a queue-based approach.


from collections import deque

def topological_sort(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])
    topo_order = []

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

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

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

                            

AI Coach Tip: Topological Sort is fundamental for problems involving task scheduling, course prerequisites, or any kind of dependency resolution. Remember that it only works on Directed Acyclic Graphs (DAGs). A common follow-up question is to detect a cycle if a valid topological sort cannot be found.

Related Algorithm Guides

Explore more algorithm interview guides powered by AI coaching

Heap Vs Bst Interview Questions
AI-powered interview preparation guide
Topological Sort Algorithm Interview Questions
AI-powered interview preparation guide
Content Strategist Interview Questions
AI-powered interview preparation guide
Automated Interview Skill Gap Analysis
AI-powered interview preparation guide