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 == n1 <= n <= 1000 <= graph[u].length < n0 <= graph[u][i] <= n - 1graph[u] does not contain uAll the values of graph[u] are uniqueIf graph[u] contains v, then graph[v] contains uSee the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
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