MediumNo. 0785
Is Graph Bipartite? — LeetCode 785 Python Solution
- Pattern
- Union-Find
- Topics
- Depth-First Search, Breadth-First Search, Union Find, Graph
- Reading time
- 3 min
- Source
- leetcode.com
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
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 TrueComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0399 | Evaluate Division | Medium |
| 0547 | Number of Provinces | Medium |
| 0684 | Redundant Connection | Medium |
| 0685 | Redundant Connection II | Hard |
| 0886 | Possible Bipartition | Medium |
| 1319 | Number of Operations to Make Network Connected | Medium |
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.