Knowledge Guide
HomeDSATrees

medium Path With Given Sequence

Problem Statement

Given a binary tree and a number sequence, find if the sequence is present as a root-to-leaf path in the given tree.

Image
Image
Image
Image

Constraints:

Try it yourself

Try solving this question here:

✅ Solution Path With Given Sequence

Problem Statement

Given a binary tree and a number sequence, find if the sequence is present as a root-to-leaf path in the given tree.

Image
Image
Image
Image

Constraints:

  • 1 <= arr.length <= 5000
  • 0 <= arr[i] <= 9
  • Each node's value is between [0 - 9].

Solution

This problem follows the Binary Tree Path Sum pattern. We can follow the same DFS approach and additionally, track the element of the given sequence that we should match with the current node. Also, we can return false as soon as we find a mismatch between the sequence and the node value.

Here is the visual representation of the algorithm:

Sum of Path Nums
Sum of Path Nums

Code

Here is the code for this algorithm:

java
import java.util.*;

// class TreeNode {
//   int val;
//   TreeNode left;
//   TreeNode right;

//   TreeNode(int x) {
//     val = x;
//   }
// };

class Solution {

  public boolean findPath(TreeNode root, int[] sequence) {
    if (root == null) return sequence.length == 0;

    return findPathRecursive(root, sequence, 0);
  }

  private static boolean findPathRecursive(
    TreeNode currentNode,
    int[] sequence,
    int sequenceIndex
  ) {
    if (currentNode == null) return false;

    if (
      sequenceIndex >= sequence.length ||
      currentNode.val != sequence[sequenceIndex]
    ) return false;

    // if the current node is a leaf, add it is the end of the sequence, we have found
    // a path!
    if (
      currentNode.left == null &&
      currentNode.right == null &&
      sequenceIndex == sequence.length - 1
    ) return true;

    // recursively call to traverse the left and right sub-tree
    // return true if any of the two recursive call return true
    return (
      findPathRecursive(currentNode.left, sequence, sequenceIndex + 1) ||
      findPathRecursive(currentNode.right, sequence, sequenceIndex + 1)
    );
  }

  public static void main(String[] args) {
    Solution sol = new Solution();
    TreeNode root = new TreeNode(1);
    root.left = new TreeNode(0);
    root.right = new TreeNode(1);
    root.left.left = new TreeNode(1);
    root.right.left = new TreeNode(6);
    root.right.right = new TreeNode(5);

    System.out.println(
      "Tree has path sequence: " + sol.findPath(root, new int[] { 1, 0, 7 })
    );
    System.out.println(
      "Tree has path sequence: " + sol.findPath(root, new int[] { 1, 1, 6 })
    );
  }
}

Time Complexity

The time complexity of the above algorithm is O(N), where ‘N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once.

Space Complexity

The space complexity of the above algorithm will be O(N) in the worst case. This space will be used to store the recursion stack. The worst case will happen when the given tree is a linked list (i.e., every node has only one child).

🤖 Don't fully get this? Learn it with Claude

Stuck on Path With Given Sequence? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Path With Given Sequence** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Path With Given Sequence** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Path With Given Sequence**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Path With Given Sequence**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes