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- A. 4
- B. 2
- C. 3
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? // directed graph with edge weights Edges: A->B 4, A->C 1, C->B 2, B->D 1, C->D 5…
- What will be the output of the following pseudocode? // directed edges: 5->2, 5->0, 4->0, 4->1, 2->3, 3->1 Compute indegree of every…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer n = 0, digitsA = 0…
- What will be the output of the following pseudocode? Function odd(Integer n) if (n == 0) return 0 end if return odd(n - 1) + 2 n - 1 End…
- What will be the output of the following pseudocode? ((mask >> i) & 1 is evaluated before ==; ^ is XOR) Integer a[3] = {5, 1, 6}, total =…
- What will be the output of the following pseudocode? (+ joins strings) String s = "PAYPALISHIRING" Integer rows = 3, r = 0, step = 1…