Skip to content
BytePatterns

Two Colour Split Check

MediumGraphs#bfs#graph-colouring~30m

Problem

An undirected graph is given as a neighbour list, where entry i holds the nodes joined to node i. Decide whether the nodes can be split into two groups so that every edge joins a node in one group to a node in the other. The graph may be disconnected, so every part has to be checked.

Examples

Input:  adj = [[1, 3], [0, 2], [1, 3], [0, 2]]
Output: True
Why:    the four-node ring alternates between the two groups
Input:  adj = [[1, 2, 3], [0, 2], [0, 1, 3], [0, 2]]
Output: False
Why:    nodes 0, 1 and 2 form a triangle, and a triangle cannot alternate
Input:  adj = [[]]
Output: True
Why:    edge case, a lone node with no edges satisfies the rule

Hints

0 / 3

Stuck on the idea rather than the code? Bipartite Check covers it.