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
35 changes: 32 additions & 3 deletions graphs/possible_bipartition.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,37 @@ 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(N+E)
Space Complexity: O(N)
"""
pass
Comment on lines +8 to -11

Choose a reason for hiding this comment

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

👍 Nice DFS solution.

if not dislikes:
return True

frontier = [0]
visited = {}
group1 = set()
group2 = set()

while frontier:
current = frontier.pop(0)

if not dislikes[current]:
if (current+1) not in visited:
visited[current+1] = True
frontier.append(current+1)
Comment on lines +22 to +25

Choose a reason for hiding this comment

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

Interesting way to approach nodes with no neighbors.


for neigbor in dislikes[current]:
if neigbor not in visited:
visited[neigbor] = True
frontier.append(neigbor)

if current not in group1:
if neigbor in group2:
return False
group1.add(neigbor)
else:
if neigbor in group1:
return False
group2.add(neigbor)

return True