← Back to Graphs Part 2

Count In-Degrees

4 of 7

Exercise 4: Count In-Degrees πŸ“₯

Your Task

Write a function count_indegrees(num_nodes, edges) that returns a dictionary mapping each node to its in-degree β€” how many edges point to it.


Examples

print(count_indegrees(4, [[0,1], [0,2], [1,3], [2,3]])) # Output: {0: 0, 1: 1, 2: 1, 3: 2} # Node 3 has 2 edges pointing to it (from 1 and 2) print(count_indegrees(3, [[0,1], [1,2], [2,0]])) # Output: {0: 1, 1: 1, 2: 1} # Each node has exactly one incoming edge print(count_indegrees(3, [])) # Output: {0: 0, 1: 0, 2: 0} # No edges β€” all in-degrees are 0 print(count_indegrees(4, [[0,3], [1,3], [2,3]])) # Output: {0: 0, 1: 0, 2: 0, 3: 3} # Node 3 is a "collector" β€” three nodes point to it

Expected Complexity

Complexity
TimeO(V + E)
SpaceO(V)

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


Approach

  1. Initialize every node's in-degree to 0
  2. For each edge [a, b], increment the in-degree of b (the destination)
  3. Return the dictionary

Key insight: Only the destination matters for in-degree. Edge [a, b] adds 1 to b's in-degree, not a's.


Starter Code

def count_indegrees(num_nodes, edges): # Your code here pass # Test your function: print(count_indegrees(4, [[0,1], [0,2], [1,3], [2,3]])) # Output: {0: 0, 1: 1, 2: 1, 3: 2} print(count_indegrees(3, [[0,1], [1,2], [2,0]])) # Output: {0: 1, 1: 1, 2: 1} print(count_indegrees(3, [])) # Output: {0: 0, 1: 0, 2: 0} print(count_indegrees(4, [[0,3], [1,3], [2,3]])) # Output: {0: 0, 1: 0, 2: 0, 3: 3} print(count_indegrees(5, [[0,1], [0,2], [1,3], [2,3], [3,4]])) # Output: {0: 0, 1: 1, 2: 1, 3: 2, 4: 1}

Hints

Try it yourself

Code: Count In-Degrees

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