Verify That a Proposed Network Topology Forms a Valid Tree
Last updated: November 29, 2026
Quick Overview
Given n routers labeled 0 to n-1 and a list of undirected links, return True if the links form a single tree: every router connected and no cycles.
0
0
0 solved
Given n routers labeled 0 to n-1 and a list of undirected links, return True if the links form a single tree: every router connected and no cycles.
A technical screen question framed around a spanning-tree style network plan, where a loop would cause broadcast storms and a gap would strand a site. The interviewer checks that you know the two conditions of a tree and can test them with either a traversal or union-find.
What the Interviewer Expects
- State that a tree has exactly n - 1 edges and is connected
- Use the edge count as a fast rejection
- Check connectivity with BFS or DFS from any node
- Alternatively detect cycles with union-find
- Handle n equal to 1 with no edges
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Return which link closes the first cycle.
- If links arrive one at a time, report the first moment the graph becomes a tree.
- What if the links are directed and you need a rooted tree?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input:
n,edgesas undirected pairs. - Output:
Trueif the graph is a tree. - No self-loops assumed, but duplicates should be handled (a duplicate edge is a cycle)....
High-Level Design
A graph on nodes is a tree if and only if any two of these hold: it is connected, it is acyclic, it has exactly edges. So the cleanest check is: if len(edges) != n - 1, return False; o...