progress

~/problems / Graphs / Bipartite graphs / 2-colouring

Colour by BFS depth, find the bad edges

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

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]]:

  1. BFS from node 0 to get each node's depth.
  2. Colour node v with depth[v] % 2.
  3. 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
A triangle 0-1-2 with a tail 2-3, nodes coloured by BFS depth parity; the edge between 1 and 2 joins two same-coloured nodes and is marked as the bad edge closing an odd cycle.
Triangle example: cyan is even depth, pink is odd depth
# 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.

Topic: Bipartite graphs / 2-colouring. BFS/DFS colouring; an odd cycle means not bipartite.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc