Skip to content
Open

Ruiz #27

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

COLORS = ["blue", "green"]

def dfs(dislikes, current_node, painted_graph, current_color):
neighbors = dislikes[current_node]
next_color = (current_color + 1) % len(COLORS)

for neighbor in neighbors:
color = painted_graph.get(neighbor)

if not color:
painted_graph[neighbor] = COLORS[next_color]
if not dfs(dislikes=dislikes, current_node=neighbor, painted_graph=painted_graph, current_color=next_color):
return False
elif color != COLORS[next_color]:
return False

return True


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)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏱ Time complexity is actually O(N + E) here where N is the number of nodes in dislikes and E is the number of edges in the graph. This is because depth first search will traverse each node and edge once.

Space Complexity: o(n)
"""
pass
painted_graph = {}
current_color = 0

for node in range(len(dislikes)):
neighbors = dislikes[node]
if not painted_graph.get(node):
painted_graph[node] = COLORS[current_color]

if not dfs(dislikes=dislikes, current_node=node, painted_graph=painted_graph, current_color=current_color):
return False
return True


# struggled with an small syntax error and then looked at leetcode answers and solution and noticed i had set it up backwards.