ProgrammingHardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer parent[1..8]
for (each i from 1 to 8) parent[i] = i
Function find(Integer x)
    while (parent[x] != x) x = parent[x]
    return x
End Function
Integer comps = 8
for each edge (a, b) in {(1, 2), (3, 4), (2, 3), (5, 6), (1, 4), (7, 7)}
    Integer ra = find(a), rb = find(b)
    if (ra != rb)
        parent[ra] = rb
        comps = comps - 1
    end if
end for
Print comps
  1. A. 4
  2. B. 2
  3. C. 3
  4. D. 5

Correct answer: A. 4

Union–find merges components only when the roots differ. (1,2), (3,4), (2,3) join {1, 2, 3, 4}; (5,6) joins {5, 6}; (1,4) is already inside one component; (7,7) is a self-loop. Components: {1,2,3,4}, {5,6}, {7}, {8} → 4.

More Pseudocode and Code Tracing questions

Exams that ask this topic