"""Topological sort (Kahn's algorithm).

Idea
----
Order the nodes of a directed acyclic graph (DAG) so every edge u -> v puts
u before v: think "build order" or "course prerequisites". Kahn's algorithm
repeatedly removes a node with no remaining incoming edges (in-degree 0) and
lowers the in-degree of its neighbours. If some nodes never reach in-degree
0, the graph has a cycle and no valid order exists.

Complexity
----------
Time:  O(V + E)
Space: O(V)
"""

from collections import deque
from collections.abc import Hashable, Mapping, Sequence
from typing import TypeVar

N = TypeVar("N", bound=Hashable)


def topological_sort(graph: Mapping[N, Sequence[N]]) -> list[N]:
    """Return a topological order; raise ValueError if there is a cycle."""
    indegree: dict[N, int] = {}
    for node, neighbours in graph.items():
        indegree.setdefault(node, 0)
        for nxt in neighbours:
            indegree[nxt] = indegree.get(nxt, 0) + 1
    queue = deque(node for node, d in indegree.items() if d == 0)
    order: list[N] = []
    while queue:
        node = queue.popleft()
        order.append(node)
        for nxt in graph.get(node, ()):
            indegree[nxt] -= 1
            if indegree[nxt] == 0:
                queue.append(nxt)
    if len(order) != len(indegree):
        raise ValueError("graph has a cycle; no topological order exists")
    return order
