Graphs Traversing a graph
449. Is Graph Bipartite?
You are given an undirected graph with n vertices, numbered from 0 to n - 1. graph[u] lists every
vertex that shares an edge with vertex u. An edge works in both directions, so v is in graph[u] exactly
when u is in graph[v]. The graph can come in several separate pieces, and a vertex can have no edges at all.
A graph is bipartite if we can split its vertices into two groups so that every edge joins a vertex of one group to a vertex of the other. No edge may have both ends in the same group. Every vertex goes into exactly one group, and a group may be empty.
Return true if the graph is bipartite, and false if it is not.
Example 1
Input: graph = [[1, 3],
[0, 2, 4],
[1, 5],
[0, 4],
[1, 3, 5],
[2, 4]]
trueExplanation: Put vertices 0, 2 and 4 in one group and vertices 1, 3 and 5 in the other. Each of the seven edges then joins the two groups.
Example 2
Input: graph = [[1], [0], [3, 4], [2, 4], [2, 3]]
falseExplanation: Vertices 0 and 1 split fine. But vertices 2, 3 and 4 form a triangle, and any split puts two of them in the same group, with an edge between them.
Example 3
Input: graph = [[], [2], [1], []]
trueExplanation: Vertices 1 and 2 go in different groups. Vertices 0 and 3 have no edges, so either group works for them.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n == graph.length ≤ 1050 ≤ graph[u][i] < ngraph[u]does not containu.- The values in
graph[u]are distinct. - If
graph[u]containsv, thengraph[v]containsu. - All the lists together hold at most 4 × 105 entries, so the graph has at most 2 × 105 edges.
Clarifying questions
What you would ask an interviewer before writing any code.