Is the Pipe Network a Tree?
Medium · Union-Find · about 20 min
A water company has n junctions numbered 0 to n - 1. Each [a, b] in pipes is a two-way pipe between junctions a and b.
The network is a tree when both are true:
- every junction can reach every other junction through pipes, and
- there is no loop: no repeated pipe, no pipe from a junction to itself, and no cycle of pipes.
Return True / true if the network is a tree, otherwise False / false. A single junction with no pipes is a tree.
Example:
pipes_form_tree(5, [[0, 1], [0, 2], [0, 3], [1, 4]]) → True
Hints
- A pipe whose two ends already have the same leader creates a loop.
- Count the joins that really merged two groups. A tree on n junctions has exactly n - 1 of them.
- Answer true only if there was no loop and the number of real joins is n - 1.
Learn the pattern first: the Union-Find lesson.
More Union-Find problems
- Count the Rail Regions (Easy)
- Can These Devices Talk? (Easy)
- The Cable That Closes a Loop (Medium)
- Merge Duplicate Contact Cards (Hard)