Data Structures & AlgorithmsModerateTCS NQT · 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 cycle'.
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 cycle'.
p = list(range(3))
def f(x):
while p[x] != x:
x = p[x]
return x
res = 'no cycle'
for u, v in [(0, 1), (1, 2), (2, 0)]:
a, b = f(u), f(v)
if a == b:
res = 'cycle'
else:
p[a] = b
print(res)What is printed?- A. no cycle
- B. cycle
- C. 2
- D. undefined
Correct answer: B. cycle
The third edge joins two vertices already in one set, which is exactly the cycle test for undirected graphs with union-find.
More Coding Interview Problems questions
- 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…
- 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…