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

Dianna T. #5

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
65 changes: 64 additions & 1 deletion lib/possible_bipartition.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,67 @@
# Depth First Search
# Time: O(n + e) where n is the number of nodes in the graph and e is the number of edges.
# Space: O(n) where n is the number of nodes in the graph.
def possible_bipartition(dislikes)

Choose a reason for hiding this comment

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

Nice work of using Depth-First-Search to solve this .

total_puppies = dislikes.length
groups = {}
stack = []

total_puppies.times do |i|
if !groups[i]
stack.push(i)
groups[i] = 1
end

while !stack.empty?
current = stack.pop
neighbors = dislikes[current]

neighbors.each do |puppy|
if !groups[puppy]
stack.push(puppy)
groups[puppy] = groups[current] * (-1)
else
if groups[puppy] == groups[current]
return false
end
end
end
end
end

return true
end

# Breadth First Search
# Time: O(n + e) where n is the number of nodes in the graph and e is the number of edges.
# Space: O(n) where n is the number of nodes in the graph.
def possible_bipartition(dislikes)
raise NotImplementedError, "possible_bipartition isn't implemented yet"
total_puppies = dislikes.length
groups = {}
queue = []

total_puppies.times do |i|
if !groups[i]
queue.push(i)
groups[i] = 1
end

while !queue.empty?
current = queue.shift

Choose a reason for hiding this comment

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

Just a note that .shift is an O(n) operation, so it would impact your runtime.

neighbors = dislikes[current]

neighbors.each do |puppy|
if !groups[puppy]
queue.push(puppy)
groups[puppy] = groups[current] * (-1)
else
if groups[puppy] == groups[current]
return false
end
end
end
end
end

return true
end