KatInterview

Verify Root Sequence Match in N-ary Tree

Trees & GraphsAuto-graded · 24 test cases
EasyAuto-gradedTrees & Graphstrees-graphsrecursiondfs

Last 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": int representing the node's value.
  • "children": List[Dict] containing child node dictionaries (can be empty or omitted).

A path matches path if:

  1. The path starts at the root node.
  2. Each step in the path moves from a parent node to one of its direct children.
  3. The length of the path equals len(path).
  4. The $i$-th node along the path has a "val" equal to path[i] for all $0 \le i < \text{len}(path)$.

Special Rules & Edge Cases:

  • An empty sequence path = [] should return True.
  • If root is None and path is not empty, return False.
  • 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 path match.
  • 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.