Data Structures & AlgorithmsModerateCognizant · Capgemini pattern
What is printed? (detect a cycle in an undirected graph with union-find)
What is printed? (detect a cycle in an undirected graph with union-find)
def has_cycle(n, edges):
p = list(range(n))
def f(x):
while p[x] != x: x = p[x]
return x
for u, v in edges:
a, b = f(u), f(v)
if a == b: return (u, v)
p[a] = b
return None
print(has_cycle(4, [(0, 1), (1, 2), (2, 3)]), has_cycle(4, [(0, 1), (2, 3), (1, 3), (0, 2)]))- A. None (1, 3)
- B. None (0, 2)
- C. (2, 3) (0, 2)
- D. None None
Correct answer: B. None (0, 2)
An edge whose endpoints already share a root closes a cycle. The path 0–1–2–3 has none. In the second graph 0–1, 2–3 and 1–3 join everything; 0–2 then closes the cycle 0–1–3–2–0. Near O(E α(V)) with path compression.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- What is printed? (number of paths from source to target in a DAG with memoisation) python from functools import lrucache g = {0: [1, 2…
- What is printed? (longest path in a DAG using topological order) python g = {'A': [('B', 3), ('C', 2)], 'B': [('D', 4)], 'C': [('D', 1)…
- What is printed? (unique paths count with memoised recursion vs closed form) python from functools import lrucache from math import comb…
- What is printed? (LIS length with O(n²) DP and the number of LIS) python a = [1, 3, 5, 4, 7] n = len(a); L = [1] n; C = [1] n for i in…
- What is printed? (coin change: number of combinations) python def ways(coins, amt): dp = [1] + [0] amt for c in coins: for a in range(c…
- What is printed? (rod cutting – maximise revenue) python price = [0, 1, 5, 8, 9, 10, 17, 17, 20] n = 8; r = [0] (n + 1) for j in range(1…