Possible Bipartition — LeetCode 886 Python Solution

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

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

Python
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

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

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

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.

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