← Back to Algorithms, page 4

algorithms-0072 · Medium fresher

Check whether a graph is bipartite: decide if its nodes can be split into two groups so that every edge connects nodes from different groups.

Try to colour the graph with two colours using BFS: give the start colour 0, every neighbour the opposite colour, and fail if an edge joins two nodes of the same colour. Repeat from each uncoloured node to cover all components. A graph is bipartite exactly when it has no odd-length cycle. Time O(V + E).

Full answer

Problem

Given an undirected graph as adjacency lists for nodes 0..n-1, return True if it is bipartite.

Example: a 4-cycle 0-1-2-3-0 is bipartite (groups {0, 2} and {1, 3}); a triangle is not.

Constraints: up to 100 nodes in the classic version, up to 10^5 in larger variants; the graph may be disconnected; a self-loop makes it non-bipartite.

Brute force

Try all 2^n assignments of nodes to two groups and check every edge: O(2^n * E).

Optimal approach

BFS two-colouring:

  1. color = [-1] * n.
  2. For each uncoloured node s: colour it 0 and BFS.
  3. For each neighbour v of u: if uncoloured, give it 1 - color[u] and enqueue; if it has the same colour as u, return False.
  4. If every component finishes, return True.

Why it works

Within one component, once the start colour is fixed, every other node's colour is forced: it must differ from its BFS parent. So if any valid split exists, BFS finds it, and a conflict means no split exists. A conflict always comes from an odd cycle, because walking around a cycle flips colour at each edge, which returns to the start colour only after an even number of steps.

Complexity

O(V + E) time, O(V) space.

Code

python
import random
from collections import deque
from itertools import product


def is_bipartite(adj):
    """2-colour each component with BFS. Fails when an edge joins two nodes of the same colour.
    O(V + E). adj is a list of neighbour lists (undirected)."""
    n = len(adj)
    color = [-1] * n
    for s in range(n):
        if color[s] != -1:
            continue
        color[s] = 0
        q = deque([s])
        while q:
            u = q.popleft()
            for v in adj[u]:
                if color[v] == -1:
                    color[v] = 1 - color[u]
                    q.append(v)
                elif color[v] == color[u]:
                    return False         # odd cycle
    return True


def brute(adj):
    n = len(adj)
    return any(all(c[u] != c[v] for u in range(n) for v in adj[u]) for c in product((0, 1), repeat=n))


if __name__ == "__main__":
    square = [[1, 3], [0, 2], [1, 3], [0, 2]]
    triangle = [[1, 2], [0, 2], [0, 1]]
    assert is_bipartite(square) and not is_bipartite(triangle)
    assert is_bipartite([]) and is_bipartite([[]])
    assert not is_bipartite([[0]])                       # self loop
    two_parts = [[1], [0], [3, 4], [2, 4], [2, 3]]       # second component is a triangle
    assert not is_bipartite(two_parts)
    rng = random.Random(72)
    for _ in range(500):
        n = rng.randint(1, 8)
        adj = [[] for _ in range(n)]
        for _ in range(rng.randint(0, 10)):
            u, v = rng.randrange(n), rng.randrange(n)
            adj[u].append(v)
            adj[v].append(u)
        assert is_bipartite(adj) == brute(adj)
    print("all tests passed")

Save as b72_bipartite.py and run python3 b72_bipartite.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty graph and a single node (bipartite). Self-loop (not bipartite). Several components, one of them odd. Isolated nodes.

Pattern

Two-colouring by forced choices. Uses: splitting people into two teams given "dislikes" pairs, scheduling with two time slots, detecting odd cycles, and the first step of bipartite matching (job assignment, Hopcroft-Karp). Union-find also works: union each node's neighbours together and fail if a node ends up with its own neighbour.

python
import random
from collections import deque
from itertools import product


def is_bipartite(adj):
    """2-colour each component with BFS. Fails when an edge joins two nodes of the same colour.
    O(V + E). adj is a list of neighbour lists (undirected)."""
    n = len(adj)
    color = [-1] * n
    for s in range(n):
        if color[s] != -1:
            continue
        color[s] = 0
        q = deque([s])
        while q:
            u = q.popleft()
            for v in adj[u]:
                if color[v] == -1:
                    color[v] = 1 - color[u]
                    q.append(v)
                elif color[v] == color[u]:
                    return False         # odd cycle
    return True


def brute(adj):
    n = len(adj)
    return any(all(c[u] != c[v] for u in range(n) for v in adj[u]) for c in product((0, 1), repeat=n))


if __name__ == "__main__":
    square = [[1, 3], [0, 2], [1, 3], [0, 2]]
    triangle = [[1, 2], [0, 2], [0, 1]]
    assert is_bipartite(square) and not is_bipartite(triangle)
    assert is_bipartite([]) and is_bipartite([[]])
    assert not is_bipartite([[0]])                       # self loop
    two_parts = [[1], [0], [3, 4], [2, 4], [2, 3]]       # second component is a triangle
    assert not is_bipartite(two_parts)
    rng = random.Random(72)
    for _ in range(500):
        n = rng.randint(1, 8)
        adj = [[] for _ in range(n)]
        for _ in range(rng.randint(0, 10)):
            u, v = rng.randrange(n), rng.randrange(n)
            adj[u].append(v)
            adj[v].append(u)
        assert is_bipartite(adj) == brute(adj)
    print("all tests passed")

BFS two-colouring over all components, checked against all 2^n colourings on random small graphs.

Complexity

Time: O(V + E). Space: O(V). DFS colouring gives the same bound.

By level

Fresher: Colours nodes alternately with BFS and fails on a same-colour edge, using the triangle as an example. Loops over all components.

Mid: Explains why a conflict means an odd cycle and returns the two groups. Solves the dislikes-pairs variant with the same code.

Senior: Connects bipartite checks to matching and assignment problems and discusses scale for large graphs. Mentions the union-find formulation and when it is preferable for streaming edges.

Key points

  • Colour neighbours with the opposite colour
  • Same-colour edge means not bipartite
  • Not bipartite exactly when an odd cycle exists
  • Loop over all components
  • O(V + E)

Common mistakes

  • Only checking the component of node 0
  • Forgetting self-loops
  • Using 2 colours but not detecting conflicts on already coloured nodes
  • Treating directed edges as one-way

Follow-ups

  • How would you return the two groups?
  • How does bipartite matching build on this?
  • How do you split people who dislike each other into two groups?

Tips

  • Mention the odd-cycle characterization
  • Handle disconnected graphs
  • Show a triangle as the smallest failure

Evaluation rubric

  • Correct colouring
  • Covers all components
  • Explains odd cycles
  • Correct complexity