← Questions

Root-started value path in an N-ary tree

0
AmazonCodingLast asked Sep 2025

A coding interview question asked in Amazon's coding round, last asked Sep 2025. It tests trees, dfs and bfs.

You are given the root of an N-ary tree (each node has an integer val and a list of children) and a list of integers path.

Return true if there is a downward path that starts at the root, moves from parent to child at each step, and visits nodes whose values are exactly path, in order. The path may stop at any node; it does not have to reach a leaf. Return false otherwise.

Values are not unique: several siblings can share a value, and only some of them may continue the path.

class Node:
    val: int
    children: list["Node"]

def path_exists(root: Node | None, path: list[int]) -> bool: ...

Constraints

  • The tree has between 1 and 10^4 nodes.
  • Node values are positive integers up to 10^5.
  • 1 <= len(path) <= 1000.

Example 1

        1
     /  |  \
    2   3   2
   /        |  \
  4         5   4
            |
            6
  • path = [1, 2, 5, 6] → true (through the third child of the root, not the first).
  • path = [1, 2, 5] → true (the path may end before a leaf).
  • path = [1, 3, 5] → false.

Example 2

Same tree, path = [2, 4] → false, because the path must start at the root.

Be ready to return the matching nodes themselves, not only a boolean.

Clarifying questions

  • Should root = None return false for any path?
  • Must the first element of path equal the root's value, as Example 2 implies?
  • Is the tree deep enough that recursion depth matters?

What a strong answer covers

  • Checks the root's value first, then keeps a frontier of nodes that match the path so far, replacing it with their children that match the next value; returns true when the path is used up and the frontier is not empty.
  • Handles duplicate sibling values by keeping every matching sibling in the frontier, not just the first (Example 1's path goes through the third child).
  • Visits each node at most once: O(number of nodes) time, O(width) memory, and no recursion.
  • Allows the path to end at an inner node, and returns false when it is longer than any branch.
  • Tests the examples, a path longer than the tree's depth, a one-node tree and an empty tree.

Follow-ups

  • Return the matching nodes themselves, for one match or every match.
  • Allow the path to start at any node, not only the root.
  • Answer many path queries on the same tree (a trie over root-to-node value sequences).

Where it's asked

  • Amazon · Coding · Last asked Sep 202555 min · Usually two rounds; one is often an object-oriented design built in steps · No AI

What it tests

trees · dfs · bfs

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding