PPractick

DSA interview question

Graph Basics: Is This Undirected Graph a Tree?

Easy · Data structures · Topics: graph, theory

The problem

A network team is designing a cabling plan for n offices, listed as undirected links between office numbers. The plan must be a tree: every office reachable from every other, and no redundant loops. This introduces the core graph vocabulary: vertices, edges, adjacency lists, connectivity and cycles. One quick fact does most of the work. A graph with n vertices is a tree exactly when it has n − 1 edges and is connected. So count the edges, then run a BFS from vertex 0 and check that it reaches everyone.

Example: n = 5, edges [[0,1], [0,2], [0,3], [1,4]] → true.

Function signature

bool isTree(int n, const vector<pair<int, int>>& edges);  // vertices 0..n-1, n >= 1

Test cases

Input (n, edges)OutputExplanation
(5, [[0,1],[0,2],[0,3],[1,4]])true4 edges, connected
(5, [[0,1],[1,2],[2,3],[1,3],[1,4]])false5 edges: the cycle 1-2-3
(4, [[0,1],[2,3]])falseTwo pieces
(1, [])trueA single vertex
(2, [])falseDisconnected

(Confirm: edges are undirected; self-loops or repeated edges make it not a tree.)

How interviewers phrase it

Clarifying questions to ask

  1. Directed or undirected? (Undirected.)
  2. Are vertices numbered 0 to n − 1? (Yes.)
  3. Can there be self-loops or repeated edges? (Possibly, and they can't appear in a tree.)

Follow-ups to expect

  1. "Basic terms?"
  2. "How do you store it?"
  3. "Why n − 1 edges plus connected?"
  4. "Alternative with DSU?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in