From 74f411fd407e03f5a5d87e285112fb91b6098049 Mon Sep 17 00:00:00 2001 From: Morgan Adkisson Date: Wed, 18 Jan 2023 11:08:48 -0800 Subject: [PATCH] Implements solution for possible_biparition exercise --- graphs/possible_bipartition.py | 50 +++++++++++++++++++++++++++++----- 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/graphs/possible_bipartition.py b/graphs/possible_bipartition.py index ca55677..7f9e744 100644 --- a/graphs/possible_bipartition.py +++ b/graphs/possible_bipartition.py @@ -1,12 +1,48 @@ # Can be used for BFS -from collections import deque +from collections import defaultdict, 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: ? + """ + Will return True or False if the given graph + can be bipartitioned without neighboring nodes put + into the same partition. + Time Complexity: O(N)^2 + Space Complexity: O(N) + + Example - + input: + dislikes = { + "Fido": [], + "Nala": ["Cooper", "Spot"], + "Cooper": ["Nala", "Bruno"], + "Spot": ["Nala"], + "Bruno": ["Cooper"] + } + output: + True """ - pass + # + if len(dislikes) == 0: + return True + + play_area = {} + stack = [] + + for dog in dislikes: + # assign unassigned dog to play area + add to stack + if dog not in play_area: + stack.append(dog) + play_area[dog] = 0 + # look at stack and check neighbors + while stack: + current = stack.pop() + # assign neighbors to group + for neighbor in dislikes[current]: + if neighbor not in play_area: + stack.append(neighbor) + play_area[neighbor] = 1 - play_area[current] + elif play_area[neighbor] == play_area[current]: + return False + + return True