MediumDepth-First SearchBreadth-First SearchUnion FindGraph

1 approach, code in every language

Problem description

You are given an undirected graph with n nodes labelled from 0 to n - 1, described by an adjacency list graph, where graph[u] is the list of nodes adjacent to node u. The graph has no self-edges and no repeated edges, and every edge is listed from both endpoints.

A graph is bipartite when its nodes can be split into two disjoint sets A and B so that every edge joins a node in A with a node in B (no edge stays inside a single set).

Return true if the graph is bipartite, and false otherwise.

Example 1

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

Output: false

Nodes 1 and 2 are neighbours and would have to sit in opposite sets, but they are also both neighbours of node 0, forcing an odd cycle. No valid two-way split exists.

Example 2

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

Output: true

Placing nodes {0, 2} in one set and {1, 3} in the other makes every edge cross between the two sets.

Constraints

  • graph.length == n
  • 1 <= n <= 100
  • 0 <= graph[u].length < n
  • 0 <= graph[u][i] <= n - 1
  • graph[u] does not contain u
  • All the values of graph[u] are unique
  • If graph[u] contains v, then graph[v] contains u

After the pattern

Now solve one you haven't seen.

Two Shift Conflict Split is our own problem on the technique behind Is Graph Bipartite?: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free