Bipartite Graph

medium

Given an undirected graph with V vertices (0 .. V-1) and an edge list edges, return true if it is bipartite — its vertices can be split into two groups so that every edge connects a vertex in one group to a vertex in the other — and false otherwise.

Hints

Try to 2-colour the graph so no edge joins same-coloured vertices.
Colour each neighbour the opposite of the current vertex during BFS/DFS.
A same-coloured edge (equivalently, an odd cycle) means it isn't bipartite.

Common doubts

Colours alternate along any path, so a cycle returns to the start with a consistent colour only if its length is even; an odd cycle forces a conflict.
No — swapping all colours gives an equally valid 2-colouring, so start each component with either colour.
Either works and both are O(V+E); the colouring rule is identical.

Interview follow-ups

Return the vertices grouped by their final colour.
Matching (jobs to workers), scheduling with two shifts, and 2-SAT-style constraint checks.

Fun facts

  • LeetCode 785 — bipartiteness is the graph-colouring warm-up with just two colours.
  • Bipartite graphs are exactly the graphs with no odd cycle — a classic theorem of König.

Asked at

AmazonFacebookMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: V = 4, edges = [[0,1],[1,2],[2,3],[3,0]]
Output: true
Colours A,B,A,B work — an even cycle is bipartite.
Example 2
Input: V = 3, edges = [[0,1],[1,2],[2,0]]
Output: false
A triangle is an odd cycle; no valid 2-colouring exists.
Constraints

- 1 <= V <= 10^5 - 0 <= edges.length <= 10^5 - no self-loops or duplicate edges

Solve this problem →