Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Is an undirected graph with n nodes a tree? Check edge count = n − 1 and that union-find never sees an edge inside one component.
Problem: Is an undirected graph with n nodes a tree? Check edge count = n − 1 and that union-find never sees an edge inside one component.
def is_tree(n, edges):
if len(edges) != n - 1: return False
p = list(range(n))
def find(x):
while p[x] != x: p[x] = p[p[x]]; x = p[x]
return x
for a, b in edges:
ra, rb = find(a), find(b)
if ra == rb: return False
p[ra] = rb
return True
print(is_tree(5, [(0, 1), (0, 2), (2, 3), (2, 4)]), is_tree(5, [(0, 1), (1, 2), (2, 0), (3, 4)]), is_tree(4, [(0, 1), (2, 3)]))What is printed?- A. True False False
- B. False False False
- C. True True False
- D. True False True
Correct answer: A. True False False
A tree is connected and acyclic; with exactly n − 1 edges, 'acyclic' already implies 'connected'. The second graph has the right edge count (4) but 0-1-2 forms a cycle and 3-4 is detached – union-find catches the cycle at edge (2, 0). The third has too few edges. O(E·α(n)).
More Coding Interview Problems questions
- Problem: Build a minimum spanning tree with Prim's algorithm (lazy heap of edges) starting from node 0; report the total weight and the…
- Problem: From index i of an array you may jump to i + a[i] or i − a[i] (staying inside). Can you reach any index holding 0? (BFS.) python…
- Problem: Paint-bucket fill: recolour the 4-connected region of the start cell's colour and report how many cells changed. python def…
- Problem: Rearrange a string so no two adjacent letters are equal ("" if impossible). Greedy: always place the most frequent remaining…
- Problem: A 'closed island' is a group of 0-cells (land) connected 4-directionally that does NOT touch the grid border. Count them. python…
- Problem: On a board of 'X' and 'O', capture every 'O' region not connected to the border by turning it into 'X'. Mark border-connected…