oneby7

Graphs Traversing a graph

449. Is Graph Bipartite?

Medium

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

012345

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

Output: true

Explanation: 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

01234

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

Output: false

Explanation: 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

0123

Input: graph = [[], [2], [1], []]

Output: true

Explanation: 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.

graph = [[], [2, 3], [1, 3], [1, 2]]

Constraints

  • 1 ≤ n == graph.length ≤ 105
  • 0 ≤ graph[u][i] < n
  • graph[u] does not contain u.
  • The values in graph[u] are distinct.
  • If graph[u] contains v, then graph[v] contains u.
  • 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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.