LeetCode #785 Medium

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 true if 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.
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.
  • If graph[u] contains v, then graph[v] contains u.
graphbfsdfscoloring
Open on LeetCode ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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).

1

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.

2

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.

3

Pop a node and check each neighbour

Pop u from the stack and look at every v in graph[u]:

  • No colour yet: give v the colour 1 - 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.
4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isBipartite(self, graph: List[List[int]]) -> bool:
▶3 color = [-1] * len(graph)
▶4 for start in range(len(graph)):
▶5 if color[start] != -1:
▶6 continue
▶7 color[start] = 0
▶8 stack = [start]
▶9 while stack:
▶10 u = stack.pop()
▶11 for v in graph[u]:
▶12 if color[v] == -1:
▶13 color[v] = 1 - color[u]
▶14 stack.append(v)
▶15 elif color[v] == color[u]:
▶16 return False
▶17 return True
not coloured123colour 0colour 10startstack0topnode 0 not coloured → colour 0, push
start0
color[0]0
stack[0]
Nothing is coloured yet. Node 0 can take either colour, because swapping the two colours of a valid split gives another valid split. Give it colour 0 and push it.
not coloured123colour 0colour 10ustackpop 0 → check its 3 neighbours
u0colour 0
graph[0][1, 2, 3]
Take node 0 off the top of the stack. Every neighbour must end up with the other colour, colour 1, so each one is looked at next.
not coloured23colour 0colour 10u1vstack1top1 not coloured → colour 1, push
v1
color[1]1opposite of 0
stack[1]
Node 1 has no colour yet. The edge 0–1 forces it onto the other side, so it gets colour 1. It is pushed so its own neighbours get checked later.
not coloured3colour 0colour 10u12vstack12top2 not coloured → colour 1, push
v2
color[2]1opposite of 0
stack[1, 2]
Node 2 has no colour yet. The edge 0–2 forces it onto the other side, so it gets colour 1. It is pushed so its own neighbours get checked later.
not colourednonecolour 0colour 10u123vstack123top3 not coloured → colour 1, push
v3
color[3]1opposite of 0
stack[1, 2, 3]
Node 3 has no colour yet. The edge 0–3 forces it onto the other side, so it gets colour 1. It is pushed so its own neighbours get checked later.
not colourednonecolour 0colour 10123ustack12toppop 3 → check its 2 neighbours
u3colour 1
graph[3][0, 2]
Take node 3 off the top of the stack. Every neighbour must end up with the other colour, colour 0, so each one is looked at next.
not colourednonecolour 0colour 10v123ustack12top0 has colour 0 → edge is fine
color[3]1
color[0]0
Node 0 is already coloured, and its colour is the opposite of 3's. This edge runs between the two groups, which is exactly what a bipartite graph needs, so nothing changes.
not colourednonecolour 0colour 1012v3ustack12top3 and 2 both colour 1 → return false
color[3]1
color[2]1
resultfalse
Nodes 3 and 2 share an edge but already hold the same colour. Their colours were both forced by earlier edges, so no choice could have avoided this. The red edges form a loop of 3 edges, an odd number, and two colours cannot alternate around an odd loop. The graph is not bipartite.
05

Common pitfalls

Only walking from node 0

✗ Wrong
color[0] = 0
stack = [0]
while stack:
    ...
✓ Right
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

✗ Wrong
elif color[v] != -1:
    return False
✓ Right
elif color[v] == color[u]:
    return False

Each 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

✗ Wrong
if not seen[v]:
    seen[v] = True
    stack.append(v)
✓ Right
if color[v] == -1:
    color[v] = 1 - color[u]
    stack.append(v)
elif color[v] == color[u]:
    return False

A 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.

06

Edge cases

A node with no edges

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.

07

Complexity

Time
O(V + E)
Space
O(V)
V is the number of nodes and E the number of edges. Each node is coloured and popped once, and each edge is looked at twice, once from each end. The colour array and the stack never hold more than V entries.
08

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.