← Google Interview Insights

Google·Software Engineer·Onsite - Coding / Algorithms·Intermediate

Intermediate
Jun 2026

Summary

Google SWE coding round, one problem the whole time: validate whether a parent array forms a valid rooted tree. Felt manageable but there are more edge cases than you'd think at first glance.

Questions Asked (1)

Q1

Given an array where each index represents a node and each value represents that node's parent (with -1 indicating the root), determine whether the structure forms a valid rooted tree.

Algorithms & Data Structures
Author's notes

My first instinct was union-find and I went with it, but I almost forgot to validate that parent values themselves are in range before doing anything else.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Clarify the definition of a valid rooted tree: exactly one root, every node except the root has exactly one parent, and no cycles. Then propose an algorithm that counts roots, validates parent references, and detects cycles, discussing time and space complexity.

Pro tip: Mention that you can solve it in O(n) time and O(n) space using an array to track visited nodes, and that you can optimize space by marking visited nodes in-place if mutation is allowed. Also, explicitly handle edge cases like empty array, multiple roots, and self-loops.

1. Clarify requirements and edge cases

Confirm the definition of a valid rooted tree and ask about constraints (e.g., array size, possible values). Discuss edge cases: empty array, multiple roots, cycles, disconnected components, and invalid parent indices.

2. Outline a validation algorithm

Propose an algorithm that checks: (1) exactly one root (-1), (2) every other node has a valid parent index, (3) no cycles, and (4) all nodes are connected to the root. Use DFS/BFS or union-find for cycle detection.

3. Analyze complexity and trade-offs

State that the algorithm runs in O(n) time and O(n) space. Discuss alternative approaches (e.g., union-find, iterative marking) and their trade-offs.

4. Walk through an example

Trace the algorithm on a small example, such as [-1, 0, 0, 1] (valid) and [-1, 0, 1, 0] (cycle), to demonstrate correctness.

5. Summarize and conclude

Reiterate the key conditions for a valid tree and confirm that the algorithm handles all cases efficiently.

Key Points to Mention

  • Exactly one root node (value -1) and all other nodes must have exactly one parent.
  • No cycles: detect using DFS with visited states or union-find.
  • All nodes must be connected to the root (no disconnected components).
  • Time complexity O(n) and space complexity O(n), with possible in-place optimization.
  • Edge cases: empty array, multiple roots, self-loops, invalid parent indices.
  • Alternative approaches: union-find, iterative marking, or topological sort.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.