Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 24 additions & 4 deletions graphs/possible_bipartition.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,32 @@
# Can be used for BFS
from collections import deque

def possible_bipartition(dislikes):
""" Will return True or False if the given graph
can be bipartitioned without neighboring nodes put
into the same partition.
Time Complexity: ?
Space Complexity: ?
Time Complexity: O(NE)
Space Complexity: O(N)
Comment on lines 3 to +8

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 I do think however that the time complexity is O(N + E) because you hit every node and check each edge that node has, but you never repeat a node.

"""
pass
# BFS solution
N = len(dislikes)
colors = [None] * N
q = deque()
for i in range(N):
if colors[i] != None:
continue
q.append((i, "red"))
while q:
node, color = q.popleft()
temp = "red"
if not colors[node]:
colors[node] = color
for next in dislikes[node]:
if colors[next] == colors[node]:
return False
elif colors[next] and colors[next] != colors[node]:
continue
elif not colors[next] and colors[node] == "red":
temp = "green"
q.append((next, temp))
return True