← Back to Graphs Part 2

Count Sink Nodes

3 of 7

Exercise 3: Count Sink Nodes πŸ”š

Your Task

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.


Examples

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

Expected Complexity

Complexity
TimeO(V + E)
SpaceO(V + E)

Where V is the number of nodes and E is the number of edges.


Approach

  1. Build the adjacency list
  2. Count nodes where the neighbor list is empty

Starter Code

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

Hints

Try it yourself

Code: Count Sink Nodes

Loading Python runtime…
Python …
Loading...
bash
$ Click "Run" to execute your code...