MediumDepth-First SearchBreadth-First SearchUnion FindGraph

Is Graph Bipartite?

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now