Data Structures & AlgorithmsModerateTCS NQT · graph warm-up
Problem: How many nodes are reachable from 0 in the directed graph with edges 0->1, 1->2, 3->0? Run the DFS code.
Problem: How many nodes are reachable from 0 in the directed graph with edges 0->1, 1->2, 3->0? Run the DFS code.
g = {0: [1], 1: [2], 2: [], 3: [0]}
seen = set()
def dfs(u):
seen.add(u)
for v in g[u]:
if v not in seen:
dfs(v)
dfs(0)
print(len(seen))What is printed?- A. 4
- B. 2
- C. 3
- D. 1
Correct answer: C. 3
From 0 the walk reaches 1 and then 2, so {0,1,2} is reachable. The edge 3->0 points into 0, not out of it.
More Coding Interview Problems questions
- Problem: Why does BFS find shortest paths in an unweighted graph in O(V + E) time?
- Problem: Which data structure supports inserting values, deleting values and answering 'how many stored values are at most x' in O(log n)…
- Problem: Which statement about the Z-function of a string of length n is correct?
- Problem: How many subarrays of [2, 3, 4, 5] contain exactly one odd number? Run the code. python a = [2, 3, 4, 5] print(sum(1 for i in…
- Problem: What is the length of the longest subarray of [1, 2, 3, 4, 5] whose sum is at most 10? Run the two-pointer code. python a = [1…
- Problem: How many pairs (i < j) of [1, 2, 3, 4, 5] have a[i] a[j] at most 10? Run the code. python a = [1, 2, 3, 4, 5] print(sum(1 for i…