Subtree Erasure in an Array-Backed Binary Tree
Trees & GraphsAuto-graded · 19 test casesLast 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 whennodesis non-empty)1 <= len(nodes) <= 10^5- Every element of
nodesis a non-negative integer (so-1is unambiguous as a sentinel) - Do not mutate the input array
- Children of node
iare at2*i + 1(left) and2*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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core observation
The array-backed binary tree has no explicit pointers, but the child relationship is just arithmetic: node i spawns children at 2*i + 1 and 2*i + 2. This means you can collect every node in a subtree using nothing but integer arithmetic and a stack — no tree-node objects needed.
Steps
1. Traverse the subtree with an iterative DFS.
Push root_idx onto a stack. On each iteration, pop an index, mark it as part of the subtree, then push its left and right children if they are within bounds. Keep going until the stack is empty.
Child indices strictly increase at every level (roughly doubling), so no index is ever visited twice and the traversal always terminates.
2. Record membership efficiently.
A bytearray of length n is the right tool here. Each entry is one byte, reads and writes are O(1), and the whole structure is far more memory-efficient than a Python set of integers (which carries 50+ bytes of overhead per entry).
3. Build both outputs in one forward pass.
Scan nodes left to right once:
- For the flagged array: emit
-1if the current index is marked, otherwise emit the original value. - For the stripped array: emit the original value only when the index is not marked.
Because this is a single left-to-right scan, the relative order of unmarked elements is preserved automatically.
4. Never touch the input.
Both output arrays are freshly allocated. The input nodes is only read, never written.
Why it is correct
Every descendant of root_idx is reachable by repeatedly applying the child formula. The DFS explores every in-bounds child of every marked node, so by induction on depth it captures the complete subtree. Conversely, the only transitions in the traversal go from a node to its children — never upward to a parent or sideways to a sibling — so no node outside the subtree is ever marked.
Complexity
| Time | O(n) — subtree traversal is O(k) where k ≤ n; both output passes are O(n) |
| Space | O(n) for the two output arrays (unavoidable) plus O(n) bytes for the mark array and O(log n) for the stack |
Edge cases
- Single element:
root_idxmust be 0. Result:([-1], []). - Root is the target: Every node is marked. Stripped array is
[]. - Target is a leaf: Both child indices fall out of bounds, so only one element is marked.
- Right child missing (partial last level): The bounds check
if right < nhandles this without special-casing.
Common pitfalls
- Mutating
nodesin place instead of building new arrays. - Filtering the flagged array by checking
value != -1— this is fragile and breaks if any input value ever equals-1. Checking the mark flag is correct regardless of value. - Using
list.pop(0)as a queue, which makes each removal O(n) and turns the whole traversal quadratic. A stack (list.pop()) orcollections.dequekeeps it linear. - Forgetting the bounds check on the right child when the last internal node has only a left child.
Reference solution
from typing import List, Tuple
def tag_and_filter_subtree(nodes: List[int], root_idx: int) -> Tuple[List[int], List[int]]:
n = len(nodes)
if n == 0:
return [], []
# One byte per index: 1 = belongs to subtree, 0 = does not
in_subtree = bytearray(n)
stack = [root_idx]
while stack:
idx = stack.pop()
if idx >= n or in_subtree[idx]:
continue
in_subtree[idx] = 1
left = 2 * idx + 1
right = left + 1
if left < n:
stack.append(left)
if right < n:
stack.append(right)
flagged = [v if not in_subtree[i] else -1 for i, v in enumerate(nodes)]
stripped = [v for i, v in enumerate(nodes) if not in_subtree[i]]
return flagged, stripped