SDE & MLE Prep

785. Is Graph Bipartite?

Problem

graph[u] lists the neighbours of node u in an undirected graph (no self-loops or duplicate edges; it may be disconnected). Decide whether its nodes can be split into two sets so that every edge joins nodes from different sets.

Example: [[1,3],[0,2],[1,3],[0,2]] → true; [[1,2,3],[0,2],[0,1,3],[0,2]] → false

Two-color each component with BFS; an edge between same colors → not bipartite (odd cycle).

Complexity: O(V + E).

class Solution:
    def isBipartite(self, graph: List[List[int]]) -> bool:
        color = [-1] * len(graph)
        for s in range(len(graph)):
            if color[s] != -1:
                continue
            color[s] = 0
            q = deque([s])
            while q:
                u = q.popleft()
                for v in graph[u]:
                    if color[v] == -1:
                        color[v] = 1 - color[u]
                        q.append(v)
                    elif color[v] == color[u]:
                        return False
        return True