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?
  1. A. True False False
  2. B. False False False
  3. C. True True False
  4. 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

Exams that ask this topic