Community Problem

Is Graph Bipartite?

Difficulty: Medium

Decide whether an undirected graph admits a 2-coloring with no edge sharing a color, using BFS over each component.

Is Graph Bipartite?

Decide whether an undirected graph admits a 2-coloring with no edge sharing a color, using BFS over each component.

MEDIUM
Free
graphs
bfs
dfs
graph-coloring

By CodeSnatch

February 26, 2026

·

Updated May 18, 2026

975 views

3

4.5 (17)

I had this on a Meta phone screen, and the conversation that followed the BFS was the actual signal: the interviewer wanted me to articulate WHY two-coloring works (no odd cycles) and what happens with disconnected components (you have to start a fresh BFS from every uncolored vertex). The catalog covers BFS but skipped this foundational two-coloring problem. The official version of this entry, that is.

Is Graph Bipartite?

There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between u and v. The graph has the following properties:

  • There are no self-edges (graph[u] does not contain u).
  • There are no parallel edges.
  • If v is in graph[u], then u is in graph[v] (the graph is undirected).
  • The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them.

A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B. Return true if and only if it is bipartite.

Examples

Example 1:

  • Input: graph = [[1, 2, 3], [0, 2], [0, 1, 3], [0, 2]]
  • Output: false
  • Explanation: There is a triangle 0 - 1 - 2 - 0, an odd cycle, so two-coloring is impossible.

Example 2:

  • Input: graph = [[1, 3], [0, 2], [1, 3], [0, 2]]
  • Output: true
  • Explanation: The graph is a 4-cycle 0 - 1 - 2 - 3 - 0. Color {0, 2} as A and {1, 3} as B. Every edge is between A and B.

Example 3:

  • Input: graph = [[]]
  • Output: true
  • Explanation: An isolated vertex is trivially bipartite.

Example 4:

  • Input: graph = [[1], [0], [3], [2]]
  • Output: true
  • Explanation: Two disconnected edges. Each component is bipartite. The whole graph is bipartite.

Constraints

  • graph.length == n.
  • 1 <= n <= 100.
  • 0 <= graph[u].length < n.
  • 0 <= graph[u][i] <= n - 1.
  • graph[u] does not contain u.
  • All the values of graph[u] are unique.
  • The graph is undirected: if graph[u] contains v, then graph[v] contains u.

Follow-up

Why is BFS two-coloring equivalent to "no odd cycle"? An odd cycle forces some vertex to be both colors at once during BFS. Conversely, if there is no odd cycle, BFS levels alternate cleanly between the two colors and the coloring is consistent.

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems