Data Structures & AlgorithmsModerateTCS NQT · BFS warm-up
Problem: What is the length of the shortest path from node 1 to node 5 in the undirected graph with edges (1,2), (2,3), (1,4), (4,5), (3,5)? Run the BFS.
Problem: What is the length of the shortest path from node 1 to node 5 in the undirected graph with edges (1,2), (2,3), (1,4), (4,5), (3,5)? Run the BFS.
from collections import deque
g = {i: [] for i in range(1, 6)}
for u, v in [(1, 2), (2, 3), (1, 4), (4, 5), (3, 5)]:
g[u].append(v)
g[v].append(u)
dist = {1: 0}
q = deque([1])
while q:
u = q.popleft()
for v in g[u]:
if v not in dist:
dist[v] = dist[u] + 1
q.append(v)
print(dist[5])What is printed?- A. 3
- B. 1
- C. 4
- D. 2
Correct answer: D. 2
The path 1-4-5 has 2 edges, shorter than 1-2-3-5 with 3 edges. BFS finds the minimum edge count.
More Coding Interview Problems questions
- Problem: How many connected components does the graph on vertices 0..5 with edges (0,1), (2,3), (4,5), (1,2) have? Run the union-find…
- Problem: Does the undirected graph with edges (0,1), (1,2), (2,0) contain a cycle? Run the union-find check and print 'cycle' or 'no…
- Problem: How many nodes are reachable from 0 in the directed graph with edges 0->1, 1->2, 3->0? Run the DFS code. python g = {0: [1], 1…
- 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?