Check path in N-ary tree
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: This question evaluates understanding of tree traversal and sequence matching in N-ary trees, including handling non-unique node values and maintaining traversal state across branches.
Constraints
- 0 <= number of nodes N <= 10^4
- 0 <= len(path) <= 10^4
- Node values fit in a 32-bit signed integer (may be negative).
- Node values are NOT guaranteed to be unique.
- children[i] contains valid node ids in the range [0, N-1]; the structure forms a tree rooted at node 0.
- An empty path matches trivially (return true).
Examples
Input: ([1, 2, 3, 4, 5], [[1, 2], [3, 4], [], [], []], [1, 2, 4])
Expected Output: True
Explanation: Root 0 (value 1) -> child node 1 (value 2) -> child node 3 (value 4). Matches [1,2,4].
Input: ([1, 2, 3, 4, 5], [[1, 2], [3, 4], [], [], []], [1, 3])
Expected Output: True
Explanation: Root 0 (value 1) -> child node 2 (value 3). The path stops at a non-leaf depth, which is allowed.
Hints
- The path is anchored at the root, so the first element of `path` must equal `values[0]`; if not, the answer is immediately false (unless the path is empty).
- Use DFS from the root carrying the current index into `path`. At each node, check its value against `path[idx]`; if it matches and idx is the last index, you are done. Otherwise recurse into the node's children with idx+1.
- Because values can repeat, a single value match is not enough — you must try every child branch that continues the prefix, returning true as soon as any branch completes the full path.
- Handle the empty-tree and empty-path boundaries explicitly: an empty path is a trivial match, and an empty tree only matches an empty path.