Can These Devices Talk?
Easy · Union-Find · about 15 min
A smart home has n devices numbered 0 to n - 1. Each [a, b] in pairs means devices a and b are paired. Pairing works both ways, and a message can hop through any number of paired devices.
For each [x, y] in questions, answer whether device x can send a message to device y. A device can always talk to itself. Return the answers as a list of booleans, in the same order as the questions.
Example:
can_devices_talk(5, [[0, 1], [1, 2], [3, 4]], [[0, 2], [0, 3], [4, 3]]) → [True, False, True]
Hints
- Build the groups once, before answering any question: union the two devices of every pairing.
- Two devices can talk exactly when their leaders (the result of find) are the same.
Learn the pattern first: the Union-Find lesson.
More Union-Find problems
- Count the Rail Regions (Easy)
- The Cable That Closes a Loop (Medium)
- Is the Pipe Network a Tree? (Medium)
- Merge Duplicate Contact Cards (Hard)