3 of 7
Write a function count_sinks(num_nodes, edges) that counts how many nodes have no outgoing edges.
A node with no outgoing edges is called a sink β nothing flows out of it.
print(count_sinks(4, [[0,1], [0,2], [1,3], [2,3]])) # Output: 1 # Only node 3 has no outgoing edges print(count_sinks(3, [[0,1], [1,2], [2,0]])) # Output: 0 # Every node has an outgoing edge print(count_sinks(3, [])) # Output: 3 # No edges at all β every node is a sink print(count_sinks(5, [[0,1], [0,2]])) # Output: 4 # Nodes 1, 2, 3, 4 have no outgoing edges
| Complexity | |
|---|---|
| Time | O(V + E) |
| Space | O(V + E) |
Where V is the number of nodes and E is the number of edges.
def count_sinks(num_nodes, edges): # Your code here pass # Test your function: print(count_sinks(4, [[0,1], [0,2], [1,3], [2,3]])) # Output: 1 print(count_sinks(3, [[0,1], [1,2], [2,0]])) # Output: 0 print(count_sinks(3, [])) # Output: 3 print(count_sinks(5, [[0,1], [0,2]])) # Output: 4 print(count_sinks(6, [[0,1], [1,2], [2,3], [3,4], [4,5]])) # Output: 1