Predict the output
What does this print?
boss = list(range(5))
def find(x: int) -> int:
while boss[x] != x:
x = boss[x]
return x
closing = None
for a, b in [(1, 2), (2, 3), (3, 4), (1, 4)]:
ra, rb = find(a), find(b)
if ra == rb:
closing = (a, b)
else:
boss[ra] = rb
print(closing)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A (1, 4)
Right: 1 and 4 are already linked through 2 and 3.
Union-find answers 'already connected?' in near-constant time, so the closing cable shows up the moment it is laid.
Why not the others?
- B (3, 4). When (3, 4) is laid, 4 is still on its own.
- C None. The fourth cable joins two offices that are already connected.