Skip to problem
←

Is Graph Bipartite?

Medium 0 attempts

You're given an undirected graph as an adjacency list graph, where graph[i] lists the neighbors of node i. Decide whether the graph is bipartite — that is, whether its nodes can be split into two groups (colored with 2 colors) so that no edge ever joins two nodes from the same group.

Function contract

Implement isBipartite(graph), where graph[v] lists the neighbors of vertex v in an undirected graph.

Output: true if all vertices can be assigned to two groups such that every edge connects different groups; otherwise false. Check every connected component.

Example 1

Input
graph = [[1,3],[0,2],[1,3],[0,2]]
Output
true

Example 2

Input
graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
Output
false
Visual Aid
Every edge crosses between the groups
0123Groups: {0, 2} and {1, 3}

The four-cycle is bipartite. An odd cycle cannot be colored with two colors without a conflict.

Constraints
  • 1 <= graph.length <= 200
  • Every neighbor is a valid vertex index.
  • The graph is undirected: every edge is listed in both directions.
  • There are no self-loops or duplicate neighbors.
Topics

BFS Coloring

Try 2-coloring the graph with BFS. If any conflict is found, it's not bipartite.

javascript
function isBipartite(graph) {
  const n = graph.length, color = Array(n).fill(-1);
  for (let i = 0; i < n; i++) {
    if (color[i] !== -1) continue;
    color[i] = 0;
    const q = [i];
    let head = 0;
  while (head < q.length) {
      const u = q[head++];
      for (const v of graph[u]) {
        if (color[v] === -1) { color[v] = 1 - color[u]; q.push(v); }
        else if (color[v] === color[u]) return false;
      }
    }
  }
  return true;
}

Time: O(V + E) | Space: O(V)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript