← Questions
Check that a parent array forms a valid tree
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's first round (coding), last asked Feb 2026. It tests trees, graphs and dfs.
You get an array parent of length n, where parent[i] is the parent of node i and -1 marks a root. Return whether the array describes one valid rooted tree: exactly one root, no cycles, and every node reachable from that root.
Interface
Unless you agree on a different interface with the interviewer, assume:
is_valid_tree(parent: list[int]) -> bool
Example
[-1, 0, 0, 1, 1] -> True # root 0
[2, -1, 1, 2] -> True # root 1; paths 0-2-1 and 3-2-1
[-1, -1] -> False # two roots
[-1, 2, 1] -> False # 1 and 2 form a cycle away from the root
[0] -> False # a node cannot be its own parent
Constraints
-
1 <= n <= 2 * 10^5. - Each
parent[i]is-1or in[0, n - 1].
Clarifying questions
- Is
-1the only root marker? - Is a self-parent (
parent[i] == i) possible, and is it invalid? - Can values fall outside
[0, n - 1]?
What a strong answer covers
- Counting roots first: exactly one
-1. - Then either build child lists and traverse from the root, checking that all
nnodes are visited; or follow parent pointers with three-color marking (or path memoization) so each node is walked once. - Why, with exactly one root and one parent per other node, "all nodes reached from the root" is enough to rule out cycles.
- O(n) time and space; iterative traversal to avoid deep recursion on a long chain.
- Tests: a single node, a long chain, a cycle with no root, two roots.
Follow-ups
- Return the depth of the tree, or of every node.
- The input is an edge list instead of a parent array.
- Find the fewest pointer changes that make the array a valid tree.
Where it's asked
- Google · First round: coding · Last asked Feb 202645 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
