Is Graph Bipartite?

MediumGraphsbfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

An undirected graph with n nodes (0 to n - 1) is given as an adjacency list: graph[u] lists every node adjacent to u. Adjacency is symmetric (v is in graph[u] exactly when u is in graph[v]), and there are no self-loops or duplicate entries. The graph may be disconnected. The graph is **bipartite** if its nodes can be split into two sets so that every edge connects a node in one set to a node in the other. Return true if the graph is bipartite, otherwise false.

Examples

Input: graph = [[1,3],[0,2],[1,3],[0,2]]
Output: true
Split into {0, 2} and {1, 3}; every edge crosses between them.
Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
Output: false
Nodes 0, 1 and 2 form a triangle, which cannot be 2-colored.

Constraints

  • 1 <= graph.length <= 1000
  • 0 <= graph[u].length < graph.length
  • 0 <= graph[u][i] < graph.length
  • graph[u] has no self-loop or repeated neighbor; adjacency is symmetric

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bfs problems