Is Graph Bipartite?

Medium Graphs

graph describes an undirected graph of n nodes, numbered from 0 to n - 1, where n is the length of graph: graph[u] lists the nodes linked to node u, and each link appears in both lists of the two nodes it joins. The graph may be in several pieces, and a node may have no links at all.

The graph is bipartite when its nodes can be split into two groups so that every link joins a node of one group to a node of the other, and no link stays inside a group.

Return true if the graph is bipartite and false if it is not.

Example 1

Input: graph = [[1,3],[0,2],[1,3],[0,2,4],[3,5],[4]]
Output: true

Put 0, 2 and 4 in one group and 1, 3 and 5 in the other. Each of the six links, around the ring 0, 1, 2, 3 and on from 3 to 4 and from 4 to 5, joins the two groups.

Example 2

Input: graph = [[1,4],[0,2],[1,3],[2,4],[3,0]]
Output: false

Example 3

Input: graph = [[1],[0],[3,4],[2,4],[2,3]]
Output: false

Constraints

  • 1 ≤ graph.length ≤ 10⁵
  • 0 ≤ graph[u][i] < graph.length, and graph[u] does not hold u
  • No node appears twice in one list, and v is in graph[u] exactly when u is in graph[v]
  • The lists hold at most 2 × 10⁵ numbers in all, so there are at most 10⁵ links

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

More Graphs

All Graphs problems