Conversation
kyra-patton
left a comment
There was a problem hiding this comment.
🐶🐾 Nice work, Cabebe. I left some comments about time complexity and edge cases below. Feel free to reach out with your questions.
🟢
| into the same partition. | ||
| Time Complexity: ? | ||
| Space Complexity: ? | ||
| Time Complexity: O(n) |
There was a problem hiding this comment.
⏱ Time complexity will actually be O(N + E) here where N is the number of nodes in the graph represented by the adjacency list dislikes and E is the number of edges in the graph. This is because as you move through your search, you will visit each node and each edge exactly once.
| for clash in dislikes: | ||
| if len(clash) > 0: | ||
| first_dog = clash[0] | ||
| break |
There was a problem hiding this comment.
🤔 This will end up working so long as clash[0] has neighbors, but I think there's a slight misunderstanding here about what dislikes holds.
The nodes (aka dogs) in dislikes are actually represented by the indices of the elements. The value at each index, is the list of neighbors (aka edges or dogs that dog [index] dislikes) that node [index] has.
For example in the graph below:
dislikes = [ [], [2,3], [1,3], [] ]
Node 0 has no neighbors.
Node 1 has an edge that points to nodes 2 and 3.
Node 2 has an edge that points to node 1 and an edge that points to node 3.
Node 3 has no edges/neighbors.
In the above example, your code would place Node 3 as the starting node, but your while loop on line 33 would finish after one iteration because Node 3 doesn't have any neighbors. There are edges pointing to Node 3, but no edges stemming from Node 3. In terms of our problem this would be because although Dogs 1 and 2 dislike Dog 3, but Dog 3 doesn't dislike Dogs 1 & 2 back.
What you would actually want to append is the first node with neighbors - which is Node 1.
(You could also imagine an edge case where you can't reach all nodes from the first node with neighbors. You could consider refactoring your code to account for this case as well).
| q.appendleft(first_dog) | ||
| seen[first_dog] = True | ||
|
|
||
| while q: |
No description provided.