MediumNo. 0886
Possible Bipartition — LeetCode 886 Python Solution
- Pattern
- Union-Find
- Topics
- Depth-First Search, Breadth-First Search, Union Find, Graph
- Reading time
- 3 min
- Source
- leetcode.com
The problem
We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.
Example
- Input
- n = 4, dislikes = [[1,2],[1,3],[2,4]]
- Output
- true
- Explanation
- The first group has [1,4], and the second group has [2,3].
Python solution
class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
def dfs(i, c):
color[i] = c
for j in g[i]:
if color[j] == c:
return False
if color[j] == 0 and not dfs(j, 3 - c):
return False
return True
g = defaultdict(list)
color = [0] * n
for a, b in dislikes:
a, b = a - 1, b - 1
g[a].append(b)
g[b].append(a)
return all(c or dfs(i, 1) for i, c in enumerate(color))Complexity
- Time
- O(V+E)
- Space · auxiliary
- O(V)
Pattern: Union-Find
Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 886. Possible Bipartition 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 |
| 0785 | Is Graph Bipartite? | Medium |
| 1319 | Number of Operations to Make Network Connected | Medium |
Frequently asked questions
- How hard is LeetCode 886. Possible Bipartition?
LeetCode 886. Possible Bipartition is rated Medium on LeetCode.
- What is the time complexity of LeetCode 886. Possible Bipartition?
The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 886. Possible Bipartition?
The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 886. Possible Bipartition cover?
LeetCode 886. Possible Bipartition is tagged Depth-First Search, Breadth-First Search, Union Find and Graph on LeetCode.