"""Bipartite check (two-colouring with BFS).

Idea
----
A graph is bipartite if its nodes can be split into two groups with every
edge going between the groups, equivalently if it has no odd-length cycle.
Colour a start node 0, colour its neighbours 1, their neighbours 0, and so on.
If an edge ever joins two nodes of the same colour, the graph is not
bipartite. Repeat from every uncoloured node to handle disconnected graphs.

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

Used for: matching problems (jobs to workers), scheduling with conflicts,
"can these people be split into two teams with no rivals together?"
"""

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

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


def two_colouring(graph: Mapping[N, Sequence[N]]) -> dict[N, int] | None:
    """Return a colour (0 or 1) for every node, or None if not bipartite.

    ``graph`` should be undirected (each edge listed in both directions).
    """
    colour: dict[N, int] = {}
    for start in graph:
        if start in colour:
            continue
        colour[start] = 0
        queue = deque([start])
        while queue:
            node = queue.popleft()
            for nxt in graph.get(node, ()):
                if nxt not in colour:
                    colour[nxt] = 1 - colour[node]
                    queue.append(nxt)
                elif colour[nxt] == colour[node]:
                    return None
    return colour


def is_bipartite(graph: Mapping[N, Sequence[N]]) -> bool:
    return two_colouring(graph) is not None
