The core fact behind 2-colouring: in a connected graph, colouring each node by its BFS depth % 2 is the only candidate 2-colouring (up to a swap). So the graph is bipartite exactly when no edge joins two nodes of the same parity; such an edge closes an odd cycle.
The graph is undirected and connected, with nodes 0 .. n-1. Implement bad_edges(n, edges) -> list[tuple[int, int]]:
- BFS from node
0to get each node's depth. - Colour node
vwithdepth[v] % 2. - Return every edge whose endpoints share a colour, as the original tuples in their original order. A self-loop is always bad.
# triangle 0-1-2 with a tail 2-3
bad_edges(4, [(0, 1), (1, 2), (2, 0), (2, 3)]) # [(1, 2)] depths: 0->0, 1->1, 2->1, 3->2
# square 0-1-2-3-0: even cycle
bad_edges(4, [(0, 1), (1, 2), (2, 3), (3, 0)]) # []
Up to 10^5 nodes and 2 * 10^5 edges.
⭐ Bonus: a speed test with 100,000 nodes earns a star in O(n + E).
Show hint
use a deque so each node gets its shortest depth, then one pass over the edges.