AI Generated Cheatsheets

Topological Sort Cheatsheet

Overview

Algorithm

def topological_sort(graph):
    # Initialize variables
    visited = set()
    stack = []

    # Visit each node in the graph
    for node in graph:
        if node not in visited:
            topological_sort_helper(graph, node, visited, stack)

    # Return the topologically sorted nodes
    return stack[::-1]

def topological_sort_helper(graph, node, visited, stack):
    # Mark the current node as visited
    visited.add(node)

    # Visit each adjacent node
    for neighbor in graph[node]:
        if neighbor not in visited:
            topological_sort_helper(graph, neighbor, visited, stack)

    # Add the current node to the stack
    stack.append(node)

Time Complexity

Resources