← Back to Graphs Part 2

Get Neighbors of a Node

2 of 7

Exercise 2: Get Neighbors of a Node πŸ”

Your Task

Write a function get_neighbors(num_nodes, edges, x) that:

  1. Builds an adjacency list from the given edge list
  2. Returns the list of direct neighbors of node x (nodes that x points to)

The graph is directed β€” edge [u, v] means there's an arrow from u to v.


Examples

print(get_neighbors(4, [[0,1], [0,2], [1,3], [2,3]], 0)) # Output: [1, 2] print(get_neighbors(4, [[0,1], [0,2], [1,3], [2,3]], 1)) # Output: [3] print(get_neighbors(4, [[0,1], [0,2], [1,3], [2,3]], 3)) # Output: [] print(get_neighbors(3, [[0,1], [1,2], [2,0]], 2)) # Output: [0]

Expected Complexity

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

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

Why? Building the adjacency list takes O(V + E). Looking up neighbors is O(1).


Approach

  1. Build the adjacency list (same as Exercise 1)
  2. Return adj[x]

Starter Code

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

Hints

Try it yourself

Code: Get Neighbors of a Node

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