Member-only story

Leetcode 886: Possible Bipartition

Wencao Yang
1 min readNov 6, 2021

--

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.

Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way.

This problem can be solved by 2-coloring, that is recursively coloring node and its neighbor until it cannot be done.

def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:         
graph = defaultdict(list)
colors = [0]*(n + 1)
for x,y in dislikes:
graph[x].append(y)
graph[y].append(x)

def dfs(curr,c):
colors[curr] = c
for n in graph[curr]:
if colors[n] == c:
return False
if colors[n] == 0 and not dfs(n,-c):
return False
return True

for g in graph:
if colors[g] == 0 and not dfs(g, 1):
return False
return True
# time complexity : O(V^2) ?
# sapce complexity : O(V) ?

--

--

Wencao Yang
Wencao Yang

Written by Wencao Yang

Data Scientist & Physics PhD

No responses yet