Predict the output
What does this print?
boss = [0, 0, 1, 2, 3]
def find(x: int) -> int:
root = x
while boss[root] != root:
root = boss[root]
while boss[x] != root:
boss[x], x = root, boss[x]
return root
print(find(4), boss)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 0 [0, 0, 0, 0, 0]
Right: the root is 0, and every node on the path now points straight at it.
Path compression pays once to flatten the chain, so later finds on these nodes take one step.
Why not the others?
- B 0 [0, 0, 1, 2, 3]. The second loop rewrites each parent on the path.
- C 4 [0, 0, 0, 0, 0]. find returns the root, which is 0.