From 8e037a5fff7a3e09d0d2a9820ae3cf9a81ce4d8f Mon Sep 17 00:00:00 2001 From: Ruge Li Date: Fri, 20 Jan 2023 12:10:17 -0800 Subject: [PATCH] pass tests --- graphs/possible_bipartition.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/graphs/possible_bipartition.py b/graphs/possible_bipartition.py index ca55677..96b04a0 100644 --- a/graphs/possible_bipartition.py +++ b/graphs/possible_bipartition.py @@ -8,5 +8,29 @@ def possible_bipartition(dislikes): Time Complexity: ? Space Complexity: ? """ - pass + + if len(dislikes) == 0: + return True + + graph = {} + color = {} + + for dislike in dislikes: + graph[dislike] = dislikes[dislike] + + for node in graph: + if node not in color: + color[node] = 0 + queue = deque() + queue.append(node) + while queue: + curr = queue.popleft() + for neighbor in graph[curr]: + if neighbor not in color: + color[neighbor] = 1 - color[curr] + queue.append(neighbor) + elif color[neighbor] == color[curr]: + return False + return True +