← Questions

Is a sequence a subsequence of a tree's in-order traversal?

0
AirbnbCodingLast asked Sep 2025

A coding interview question asked in Airbnb's technical phone screen, last asked Sep 2025. It tests trees, two pointers and morris traversal.

You get a binary tree of integers and an array target. Decide whether target is a subsequence of the tree's in-order traversal: its values appear in that order, not necessarily next to each other. Then change the tree as little as possible so that it is.

Part 1: check

Unless you agree on a different interface with the interviewer, assume:

  • is_inorder_subsequence(root, target: list[int]) -> bool: stream the traversal; don't build the in-order list. Aim for O(n) time and O(1) extra space.

Part 2: minimum edits

  • min_edits(root, target) -> int: each operation costs 1, either overwriting an existing node's value or inserting a new node anywhere in the tree. Return the fewest operations that make target a subsequence of the in-order traversal, and be ready to produce one set of edits that achieves it.

Example

tree:        6
           /   \
          3     8
         / \   /
        1   4 7          in-order: 1, 3, 4, 6, 7, 8

is_inorder_subsequence(tree, [3, 6, 8])  ->  True
is_inorder_subsequence(tree, [6, 3])     ->  False
min_edits(tree, [6, 3])                  ->  1    # e.g. overwrite 7 with 3
min_edits(tree, [1, 5, 7])               ->  1    # overwrite 3 or 4 with 5
min_edits(tree, [9, 9])                  ->  2

Constraints

  • Up to 10^5 nodes and 10^5 target values for Part 1; values may repeat.
  • Part 2 may assume smaller inputs (a few hundred each).

Clarifying questions

  • Is an empty target always a subsequence?
  • Can values repeat in the tree or the target?
  • May I modify the tree temporarily during traversal?

What a strong answer covers

  • One pointer into target, advanced on each matching in-order value; greedy matching is optimal for subsequence checks.
  • An iterative traversal with a stack (O(height) space), then Morris traversal for O(1) space, restoring the threaded pointers.
  • Part 2: every target value not matched costs exactly one operation, so the minimum is len(target) minus the longest common subsequence of the in-order values and target. O(n × m) dynamic programming, with backtracking to list the edits.
  • Edge cases: empty target, target longer than the tree, duplicates.

Follow-ups

  • Return the edited tree, not just the count.
  • Only overwrites are allowed, no inserts.
  • The target must appear contiguously.

Where it's asked

What it tests

trees · two pointers · morris traversal

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