Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C16 - Pine - Ainur #44

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
31 changes: 28 additions & 3 deletions graphs/possible_bipartition.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,33 @@ 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) N-number of nodes, E -number of edges

Choose a reason for hiding this comment

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

Space Complexity: O(N)??

Choose a reason for hiding this comment

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

🪐 Yes! Space complexity will be O(N) because the data structures you create, queue, visited, group1, and group2 can each hold at most N nodes (aka dogs).

"""
pass
if not dislikes:
return True

queue = deque()
visited = set()
group1 = set()
group2 = set()

queue.append(0)

Choose a reason for hiding this comment

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

Your two test cases are failing because you need a guard clause to find the first node in the list that is connected to other nodes in the graph.

Say you have a graph such as this:
dislikes = [ [], [2, 3], [1, 3], [1, 2] ]
If you draw out the graph, you will see that Node 0 is disconnected from the rest of the graph - it has no edges. Because it has no edges/neighbors, nothing else will be added to your queue after you pop Node 0 off the queue and you will return True by default.


while queue:
current = queue.popleft()
for neigbor_dog in dislikes[current]:
if neigbor_dog not in visited:
visited.add(neigbor_dog)
queue.append(neigbor_dog)
if current in group1:
group2.add(neigbor_dog)
else:
group1.add(neigbor_dog)
elif neigbor_dog in visited:
if current in group1 and neigbor_dog in group1:
return False
if current in group2 and neigbor_dog in group2:
return False

return True