medium

Is Graph Bipartite?

Given an undirected graph as an adjacency list, decide whether its nodes can be split into two groups such that every edge connects a node from one group to the other.

Constraints
  • 1 ≤ n ≤ 100
  • No self-loops or parallel edges
  • The graph may be disconnected
Examples
in: graph = [[1,3],[0,2],[1,3],[0,2]]
out: true
in: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
out: false
Recognition clues
  • Two groups with edges only across = 2-colouring
  • A conflict appears when a neighbour already has your colour
  • Must handle every component
Pattern
Depth-First Search

DFS follows one branch to exhaustion before backtracking, which makes it the natural tool for "which cells/nodes belong together", for enumerating complete paths, and for cycle detection via the recursion stack (gray nodes). It needs only the graph plus a visited set and is easily written recursively.

Solution

Assign colours 0/1 while traversing. For each uncoloured node, colour it 0 and DFS: every neighbour must receive the opposite colour; if a neighbour already has the same colour as the current node, an odd cycle exists and the graph is not bipartite. Repeat for every component. If no conflict is found the two colour classes are the required groups.

time O(V + E)space O(V)
Alternative approaches
  • BFS colouring by level is identical in cost and avoids recursion depth issues. Union-find with "enemy" tracking also works and suits incremental edge insertion.
Code it yourself
Solve in
Hints: