Is Graph Bipartite? — LeetCode 785 Python Solution

MediumDepth-First SearchBreadth-First SearchUnion FindGraph
Problem
#785
Pattern
Union-Find
Reading time
3 min

The problem

There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to.

Example

Input
graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
Output
false
Explanation
There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.

Python solution

Python
class Solution:
    def isBipartite(self, graph: List[List[int]]) -> bool:
        def dfs(a: int, c: int) -> bool:
            color[a] = c
            for b in graph[a]:
                if color[b] == c or (color[b] == 0 and not dfs(b, -c)):
                    return False
            return True

        n = len(graph)
        color = [0] * n
        for i in range(n):
            if color[i] == 0 and not dfs(i, 1):
                return False
        return True

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Union-Find

Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 785. Is Graph Bipartite? is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.

The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 785. Is Graph Bipartite??
LeetCode 785. Is Graph Bipartite? is rated Medium on LeetCode.
What is the time complexity of LeetCode 785. Is Graph Bipartite??
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 785. Is Graph Bipartite??
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 785. Is Graph Bipartite? cover?
LeetCode 785. Is Graph Bipartite? is tagged Depth-First Search, Breadth-First Search, Union Find and Graph on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview