Member-only story
Leetcode 886: Possible Bipartition
1 min readNov 6, 2021
We want to split a group of
n
people (labeled from1
ton
) 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 arraydislikes
wheredislikes[i] = [ai, bi]
indicates that the person labeledai
does not like the person labeledbi
, returntrue
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) ?