Data Structures & AlgorithmsModerateTCS NQT · union-find
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 code.
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 code.
p = list(range(6))
def f(x):
while p[x] != x:
p[x] = p[p[x]]
x = p[x]
return x
for u, v in [(0, 1), (2, 3), (4, 5), (1, 2)]:
p[f(u)] = f(v)
print(len({f(i) for i in range(6)}))What is printed?- A. 2
- B. 1
- C. 3
- D. 4
Correct answer: A. 2
The components are {0,1,2,3} and {4,5}, so there are 2. The edge (1,2) merges the two pairs {0,1} and {2,3}.
More Coding Interview Problems questions
- 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?
- 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…