Menu
CoddyTech

Is Graph Bipartite

MediumGraphsQueuepython iconjava iconcpp iconc iconjs icon+10

A graph has n nodes, labelled 0 to n-1. Each pair [a, b] in edges is an undirected edge between node a and node b. The graph may fall into several separate parts, and some nodes may have no edge at all.

A graph is bipartite when you can split its nodes into two groups so that every edge joins a node of one group to a node of the other. Return true if the graph is bipartite and false otherwise.

Function

isBipartite(n: integer, edges: integer-2d-array) → boolean
ninteger
the number of nodes, numbered 0 to n-1
edgesinteger-2d-array
the undirected edges, each a pair [a, b]
Returnsboolean
true if the nodes can be split into two groups with every edge between the groups, false otherwise

Constraints

  • 2 ≤ n ≤ 104
  • 1 ≤ edges.length ≤ 5000
  • edges[i] = [a, b] with 0 ≤ a, b ≤ n-1 and a ≠ b
  • No edge appears twice, in either direction.

Examples

Input
n = 4edges = [[0, 1], [1, 2], [2, 3], [3, 0]]
Output
true
Explanation
Put nodes 0 and 2 in one group and nodes 1 and 3 in the other. Each of the four edges joins the two groups.
challenge icon

Follow-up

When the graph is not bipartite, can you return one cycle of odd length as proof, listing its nodes in order?

Reset code
def isBipartite(n, edges):
    # Write code here

Test #1

Test #2

Test #3

Arguments

n = 4
edges = [[0, 1], [1, 2], [2, 3], [3, 0]]

Expected Output

true