KatInterview

Subtree Erasure in an Array-Backed Binary Tree

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphstrees-graphsarraysbfs-dfs

Last updated

Tests implicit heap-tree traversal, subtree identification via index arithmetic, and stable compaction without mutating the input array.

Problem Statement

A binary tree can be stored compactly in a plain array: the node at index i has its left child at index 2*i + 1 and its right child at index 2*i + 2. There are no pointers — the structure is entirely encoded in the indices.

You are given such an array nodes and an index root_idx. Your task is to produce two new arrays based on the subtree rooted at root_idx. The original array must not be modified.

Step 1 — Flag the subtree. Collect every index that belongs to the subtree rooted at root_idx (the node itself plus all of its descendants). Build a new array of the same length as nodes where each position in the subtree is replaced by -1 and every other position keeps its original value.

Step 2 — Strip the subtree. Build a second new array containing only the values at positions that were not part of the subtree, in the same left-to-right order they appeared in nodes.

Return both arrays as a tuple: (flagged_array, stripped_array).

Constraints

  • 0 <= root_idx < len(nodes) (guaranteed when nodes is non-empty)
  • 1 <= len(nodes) <= 10^5
  • Every element of nodes is a non-negative integer (so -1 is unambiguous as a sentinel)
  • Do not mutate the input array
  • Children of node i are at 2*i + 1 (left) and 2*i + 2 (right); any child index >= len(nodes) does not exist

Examples

Example 1

Input: tag_and_filter_subtree([10, 20, 30, 40, 50], 1)

Output: [[10, -1, 30, -1, -1], [10, 30]]

Example 2

Input: tag_and_filter_subtree([5, 2, 8], 0)

Output: [[-1, -1, -1], []]

Example 3

Input: tag_and_filter_subtree([7], 0)

Output: [[-1], []]

Hints

Hint 1

You don't need to build any node objects. The child indices follow a fixed formula, so you can traverse the subtree using a stack or queue that holds integer indices directly.

Hint 2

Use a flat boolean or byte array of length n to record which indices belong to the subtree. This gives O(1) membership checks and keeps the final two output passes simple and fast.

Hint 3

Build both output arrays in a single forward scan after the traversal: for each index, emit -1 or the original value for the first array, and skip the index entirely for the second array if it was marked.