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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

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
tree properties
BFS
union-find
cycle detection
connectivity
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample Answer
Requirements
  • Input: n, edges as undirected pairs.
  • Output: True if 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 nn nodes is a tree if and only if any two of these hold: it is connected, it is acyclic, it has exactly n−1n - 1 edges. So the cleanest check is: if len(edges) != n - 1, return False; o...


Submit Your Answer
Markdown supported