Is Graph Bipartite?
Is Graph Bipartite? is LeetCode 785 (Medium). You get an undirected graph with n nodes as an adjacency list: graph[u] lists every node joined to u by an edge.
- Return
trueif the nodes can be split into two groups so that every edge joins a node in one group to a node in the other. - The graph can be in several pieces that are not connected to each other.
- There are no self-loops or repeated edges, and every edge appears in both nodes' lists.
- 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.
- If graph[u] contains v, then graph[v] contains u.
Intuition
Trying every way to split the nodes would mean 2ⁿ checks. Instead, let the edges decide. Put one node in group 0. Every neighbour is then forced into group 1, their neighbours back into group 0, and so on, so one walk through the graph fixes every node's group.
- No choice is lost: the only free pick is the first node of each piece, and swapping the two groups of a valid split gives another valid split.
- A clash is final: if an edge joins two nodes that were forced into the same group, neither node had another option, so no split exists.
Calling the groups colours 0 and 1 turns this into two-colouring the graph.
"Split into two groups so every link crosses" is two-colouring. Seating rivals at two tables, scheduling exams into two slots, and checking that a graph has no odd cycle all reduce to it.
Approach
Before reading on, colour a square (4 nodes in a ring) and a triangle by hand with two colours, never giving both ends of an edge the same colour. Notice where the triangle gets stuck, and what forced each colour along the way. Aim for O(V + E).
Keep one colour per node
Store color[v] as -1 for a node not reached yet, or 0 or 1 for its group. The same array works as the visited marker and as the record the clash test compares against.
Start a walk from every uncoloured node
Loop over all nodes. When one still has colour -1, give it colour 0 and push it onto a stack. A node that is already coloured belongs to a piece that was fully checked from an earlier start, so skip it.
Pop a node and check each neighbour
Pop u from the stack and look at every v in graph[u]:
- No colour yet: give
vthe colour1 - color[u]and push it, so its own neighbours get checked. - The other colour: the edge already crosses between the groups, so move on.
- The same colour: return
false.
Return true when every walk ends cleanly
Once all stacks have emptied without a clash, every edge has been seen from both ends and joins two different colours. The two colour groups are a valid split, so return true.
Code in Python, C++ and Java
Common pitfalls
Only walking from node 0
color[0] = 0
stack = [0]
while stack:
...for start in range(len(graph)):
if color[start] != -1:
continue
color[start] = 0
stack = [start]In [[], [2, 3], [1, 3], [1, 2]] node 0 has no edges, so a walk from it ends at once and returns true. Nodes 1, 2 and 3 form a triangle that is never checked; the answer is false.
Treating every coloured neighbour as a clash
elif color[v] != -1:
return Falseelif color[v] == color[u]:
return FalseEach edge is seen from both ends. In [[1], [0]], popping node 1 finds node 0 already coloured 0, which is the correct opposite colour, yet this check returns false. Only a matching colour is a clash.
Using a plain visited flag instead of a colour
if not seen[v]:
seen[v] = True
stack.append(v)if color[v] == -1:
color[v] = 1 - color[u]
stack.append(v)
elif color[v] == color[u]:
return FalseA visited flag says a node was reached, not which group it is in, so there is nothing to compare. On the triangle [[1, 2], [0, 2], [0, 1]] this version returns true.
Edge cases
It gets colour 0 when the outer loop reaches it and has no neighbours to check, so it can never cause a clash. A graph with no edges at all is bipartite.
Complexity
Is Graph Bipartite? FAQ
Why does a same-colour edge mean the graph has an odd cycle?
Colours alternate along every step of the walk, so a node's colour tells you whether its path from the start node is even or odd in length. If u and v share a colour, their paths have the same parity. Follow both paths back to the node where they meet, then add the edge u–v: the loop has (even + even + 1) or (odd + odd + 1) edges, which is odd either way. Two colours cannot alternate around an odd loop, so no split exists.
Should I use BFS or DFS?
Either one. Only the order of visits changes; the colour rule and the clash test stay the same. Swap the stack for a queue that pops from the front and you have the BFS version. A recursive DFS works too, since 100 nodes keeps the recursion shallow.
Can union-find solve it?
Yes. All neighbours of a node must sit in the same group, so union them together, and return false as soon as a node shares a set with one of its own neighbours. It costs about the same, but colouring is easier to explain in an interview.
How is this different from Possible Bipartition?
Possible Bipartition (LeetCode 886) asks the same question about people and dislikes, but gives a list of pairs numbered from 1, so you build the adjacency list first. Here the adjacency list is the input and nodes start at 0.