Validate parent array forms a tree
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's understanding of tree and graph fundamentals, specifically parent-pointer representations, root identification, cycle detection, and connectivity invariants. Commonly asked in the Coding & Algorithms domain to assess reasoning about graph structure and invalid configurations, it requires both conceptual understanding and practical application.
Constraints
- 1 <= n <= 2 * 10^5
- Each `parent[i]` is either `-1` or an integer in `[0, n-1]`
- `parent[i] = i` is invalid
Examples
Input: [-1, 0, 0, 1, 1]
Expected Output: True
Explanation: Node 0 is the only root. All other nodes are connected under it, and there are no cycles.
Input: [2, -1, 1, 2]
Expected Output: True
Explanation: Node 1 is the root. The paths are 0->2->1, 2->1, and 3->2->1, so every node reaches the same root.
Input: [-1]
Expected Output: True
Explanation: A single node with parent -1 is a valid rooted tree.
Input: []
Expected Output: False
Explanation: An empty array has no root, so it cannot form a valid rooted tree.
Input: [-1, -1, 0]
Expected Output: False
Explanation: There are two roots, so the structure is not a single rooted tree.
Input: [1, 2, 0]
Expected Output: False
Explanation: All nodes form a cycle and there is no root.
Input: [-1, 0, 3, 2]
Expected Output: False
Explanation: Nodes 2 and 3 form a separate cycle, so not all nodes belong to the same rooted structure.
Input: [-1, 0, 5]
Expected Output: False
Explanation: Node 2 points to parent 5, which is outside the valid index range.
Solution
def solution(parent):
n = len(parent)
if n == 0:
return False
root = -1
root_count = 0
children = [[] for _ in range(n)]
for i, p in enumerate(parent):
if p == -1:
root_count += 1
root = i
else:
if p < 0 or p >= n:
return False
children[p].append(i)
if root_count != 1:
return False
visited = [False] * n
stack = [root]
visited[root] = True
seen = 0
while stack:
node = stack.pop()
seen += 1
for child in children[node]:
if visited[child]:
return False
visited[child] = True
stack.append(child)
return seen == nTime complexity: O(n). Space complexity: O(n).
Hints
- First count how many roots there are. A valid tree must have exactly one `-1` entry.
- Build children lists from the parent array, then traverse from the root. If you do not visit every node, the structure is disconnected or contains a cycle away from the root.