791. Is It a Tree
A gardener plans an irrigation layout with n junctions numbered 0 to n - 1. Each entry [a, b] in edges is a two-way pipe between junctions a and b.
The layout is a branching network when water can get from any junction to any other, and between every two junctions there is exactly one route that never repeats a pipe. In other words it is connected and has no closed loops. Return true if the layout is a branching network and false otherwise. A pipe from a junction to itself, and two pipes between the same pair of junctions, both count as loops. A single junction with no pipes is a valid network.
Example 1
- Input:
- n = 6, edges = [[3,0],[3,1],[1,2],[4,1],[5,4]]
- Output:
- true
- Explanation:
Six junctions and five pipes, all hanging off each other without any closed loop: every junction is reachable by exactly one route.
Example 2
- Input:
- n = 5, edges = [[0,1],[1,2],[2,3],[3,1]]
- Output:
- false
- Explanation:
Pipes 1-2, 2-3 and 3-1 form a closed loop, which also leaves junction 4 cut off.
Example 3
- Input:
- n = 5, edges = [[0,1],[2,3],[3,4]]
- Output:
- false
- Explanation:
Junctions 0 and 1 form a separate piece from junctions 2, 3 and 4, so the layout is not connected.
Constraints
- 1 ≤ n ≤ 105
- 0 ≤ edges.length ≤ 2 * 105
- 0 ≤ a, b < n for every
[a, b]
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 300 msC++ 75 msJava 150 msJavaScript 150 msTypeScript 150 ms
Expected complexity
- Time
- O((n + m) * alpha(n))
- Space
- O(n)