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
38 changes: 34 additions & 4 deletions graphs/possible_bipartition.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,42 @@
# Can be used for BFS
from collections import deque
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 4 to 10

Choose a reason for hiding this comment

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

I think this is O(N + E) for time complexity because I think you hit every node and check every edge that node has.

pass

if not dislikes:
return True

visited = [False] * len(dislikes)
group_a = set()
group_b = set()

q = deque()
q.append(0)

while q:
current = q.popleft()
visited[current] = True
if not dislikes[current]:
q.append(current+1)

for dog in dislikes[current]:
if not visited[dog]:
q.append(dog)

if current not in group_a:
if dog in group_b:
return False
group_a.add(dog)
else:
if dog in group_a:
return False
group_b.add(dog)

return True