Ecommet

Is Graph Bipartite?

Medium Problem 108 of 151 Java and Python

Problem

You are given an undirected graph with n nodes as an adjacency list graph, where graph[u] lists the neighbours of u. The graph may be disconnected.

Return true if the graph is bipartite: its nodes can be split into two sets so that every edge connects a node in one set to a node in the other.

Example 1

Input
graph = [[1, 3], [0, 2], [1, 3], [0, 2]]
Output
true
Why
Sets {0, 2} and {1, 3}.

Example 2

Input
graph = [[1, 2, 3], [0, 2], [0, 1, 3], [0, 2]]
Output
false
Why
0, 1 and 2 form a triangle.

Constraints

  • 1 ≤ n ≤ 100
  • No self-loops or repeated edges; the graph is undirected.

Explanation

Try to colour the graph with two colours so neighbours always differ. Start any uncoloured node with colour 0; its neighbours must be 1, their neighbours 0, and so on. If you ever find two neighbours with the same colour, it cannot be done (there is an odd cycle).

Repeat from every uncoloured node, because the graph may have several components.

Approach 1 · Better

DFS two-colouring

  • Time O(V + E)
  • Space O(V)

Recursively colour neighbours with the opposite colour, failing on a conflict.

  1. colour[] starts at -1 (uncoloured).
  2. dfs(u, c): set colour[u] = c; for each neighbour, fail if it has colour c; recurse with 1 - c if uncoloured.
  3. Run from every uncoloured node.
Java
import java.util.*;

class Solution {
    public boolean isBipartite(int[][] graph) {
        int[] colour = new int[graph.length];
        Arrays.fill(colour, -1);
        for (int u = 0; u < graph.length; u++) {
            if (colour[u] == -1 && !paint(graph, u, 0, colour)) {
                return false;
            }
        }
        return true;
    }

    private boolean paint(int[][] graph, int u, int c, int[] colour) {
        colour[u] = c;
        for (int v : graph[u]) {
            if (colour[v] == c) {
                return false;
            }
            if (colour[v] == -1 && !paint(graph, v, 1 - c, colour)) {
                return false;
            }
        }
        return true;
    }
}
Python
class Solution:
    def isBipartite(self, graph: List[List[int]]) -> bool:
        colour = [-1] * len(graph)

        def paint(u, c):
            colour[u] = c
            for v in graph[u]:
                if colour[v] == c:
                    return False
                if colour[v] == -1 and not paint(v, 1 - c):
                    return False
            return True

        return all(colour[u] != -1 or paint(u, 0) for u in range(len(graph)))

Approach 2 · Optimal

BFS two-colouring

  • Time O(V + E)
  • Space O(V)

Same idea, iteratively with a queue, so deep graphs cannot overflow the stack.

  1. For each uncoloured node, colour it 0 and enqueue it.
  2. Pop u; for each neighbour v: if uncoloured, give it 1 - colour[u] and enqueue; if it has the same colour as u, return false.
  3. Return true.
Java
import java.util.*;

class Solution {
    public boolean isBipartite(int[][] graph) {
        int[] colour = new int[graph.length];
        Arrays.fill(colour, -1);
        for (int start = 0; start < graph.length; start++) {
            if (colour[start] != -1) {
                continue;
            }
            colour[start] = 0;
            Deque<Integer> queue = new ArrayDeque<>();
            queue.add(start);
            while (!queue.isEmpty()) {
                int u = queue.poll();
                for (int v : graph[u]) {
                    if (colour[v] == -1) {
                        colour[v] = 1 - colour[u];
                        queue.add(v);
                    } else if (colour[v] == colour[u]) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
}
Python
from collections import deque

class Solution:
    def isBipartite(self, graph: List[List[int]]) -> bool:
        colour = [-1] * len(graph)
        for start in range(len(graph)):
            if colour[start] != -1:
                continue
            colour[start] = 0
            queue = deque([start])
            while queue:
                u = queue.popleft()
                for v in graph[u]:
                    if colour[v] == -1:
                        colour[v] = 1 - colour[u]
                        queue.append(v)
                    elif colour[v] == colour[u]:
                        return False
        return True

Complexity compared

ApproachTimeSpace
Better DFS two-colouringO(V + E)O(V)
Optimal BFS two-colouringO(V + E)O(V)

Key takeaways

  • A graph is bipartite exactly when it has no odd-length cycle.
  • Do not forget disconnected components: loop over every start node.

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem