ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
parent = list(range(5))
def find(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]
        x = parent[x]
    return x
def union(a, b):
    parent[find(a)] = find(b)
union(0, 1)
union(2, 3)
union(1, 3)
print(find(0), parent)
  1. A. 3 [0, 1, 2, 3, 4]
  2. B. 3 [3, 3, 3, 3, 4]
  3. C. 3 [1, 3, 3, 3, 4]
  4. D. 1 [1, 3, 3, 3, 4]

Correct answer: B. 3 [3, 3, 3, 3, 4]

After the three unions parent is [1, 3, 3, 3, 4]. find(0) uses path halving: parent[0] becomes parent[1], which is 3, and then the walk reaches the root 3. The array is left as [3, 3, 3, 3, 4].

More Python Programming questions

Exams that ask this topic