Verify Root Sequence Match in N-ary Tree
Trees & GraphsAuto-graded · 24 test casesLast updated
Determine if a given target sequence matches a top-down path in an N-ary tree represented by nested dictionaries.
You are given an N-ary tree represented by nested dictionaries and a list of integers path. Determine whether there exists a valid top-down path starting from the root node whose sequence of node values matches path element by element.
Each node in the tree is structured as a dictionary:
"val":intrepresenting the node's value."children":List[Dict]containing child node dictionaries (can be empty or omitted).
A path matches path if:
- The path starts at the root node.
- Each step in the path moves from a parent node to one of its direct children.
- The length of the path equals
len(path). - The $i$-th node along the path has a
"val"equal topath[i]for all $0 \le i < \text{len}(path)$.
Special Rules & Edge Cases:
- An empty sequence
path = []should returnTrue. - If
rootisNoneandpathis not empty, returnFalse. - The matching path does not need to extend to a leaf node; stopping at an intermediate node is valid as long as all elements in
pathmatch. - Siblings can have duplicate values; multiple branches may need to be considered.
Constraints
- The tree contains between $0$ and $10^4$ nodes.
- Each node's value is an integer between $-10^9$ and $10^9$.
- $0 \le \text{len}(path) \le 10^4$.
Examples
Example 1
Input: check_path({'val': 1, 'children': [{'val': 2, 'children': []}, {'val': 3, 'children': [{'val': 4, 'children': []}]}]}, [1, 3, 4])
Output: True
Example 2
Input: check_path({'val': 1, 'children': [{'val': 2, 'children': []}, {'val': 3, 'children': [{'val': 4, 'children': []}]}]}, [1, 3])
Output: True
Example 3
Input: check_path({'val': 1, 'children': [{'val': 2, 'children': []}, {'val': 2, 'children': [{'val': 3, 'children': []}]}]}, [1, 2, 3])
Output: True
Example 4
Input: check_path({'val': 1, 'children': []}, [1, 2])
Output: False
Hints
Hint 1
Consider edge cases first: what if path is empty? What if root is None?
Hint 2
Does a node value matching path[i] guarantee that its subtrees will complete path[i+1...]? Multiple children might have the same value.
Hint 3
Use a depth-first search (DFS) or breadth-first search (BFS) tracking (current_node, current_path_index) to explore all matching branches.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks if a target sequence path matches any prefix of a path starting from the root of an N-ary tree. Because multiple children of a node can share the same value, a greedy choice (following the first matching child) may lead to a dead end while another branch holds the complete sequence.
We can traverse the tree using an explicit stack (Iterative Depth-First Search) or recursion, keeping track of pairs (node, index) where index represents the current position in path.
-
Base Cases:
- If
pathis empty, returnTruetrivially. - If
rootisNone(andpathis non-empty), returnFalse.
- If
-
Traversal:
- Push
(root, 0)onto the stack. - Pop a pair
(node, index). - Check if
node["val"]matchespath[index]. If not, prune this branch. - If
node["val"]matches andindex == len(path) - 1, we have found a complete matching sequence, so returnTrue. - Otherwise, push all children of
nodepaired withindex + 1onto the stack and continue.
- Push
Complexity Analysis
- Time Complexity: $\mathcal{O}(N)$ in the worst case, where $N$ is the number of nodes in the tree. We visit each node at most once during the traversal, pruning branches early as soon as a mismatch occurs.
- Space Complexity: $\mathcal{O}(D)$ where $D$ is the maximum depth/width of the search stack. In the worst case, this is bounded by $\mathcal{O}(N)$.
Python Solution
from typing import List, Optional, Dict, Any
def check_path(root: Optional[Dict[str, Any]], path: List[int]) -> bool:
if not path:
return True
if root is None:
return False
stack = [(root, 0)]
while stack:
node, index = stack.pop()
if node.get("val") != path[index]:
continue
if index == len(path) - 1:
return True
next_index = index + 1
for child in node.get("children", []):
stack.append((child, next_index))
return False