Prune a Branch from a Parent-Array Forest
Trees & GraphsAuto-graded · 21 test casesLast updated
Remove a node and its entire subtree from a forest stored as a parent array, either by marking slots with -1 or by compacting indices and remapping parent pointers.
Prune a Branch from a Parent-Array Forest
A forest is stored in a zero-indexed list parents of length n. Entry parents[i] is the index of the parent of node i. A node that is the root of its tree stores its own index: parents[i] == i. The input is always a valid forest, so following parent links from any node always ends at a self-referencing root.
You are given a node index target and a boolean compact. Pruning removes target together with every one of its descendants, that is, every node whose chain of parents passes through target (including target itself).
Return a new list describing the forest after pruning, according to the mode:
Mark mode (compact = False)
- The result has the same length
nas the input. - For
targetand each of its descendants, the entry is set to-1. - Every other entry is left exactly as in the input, so surviving nodes keep their indices and parent values.
Compact mode (compact = True)
- Removed nodes are dropped from the list entirely.
- The surviving nodes keep their relative order and are renumbered consecutively from
0tok - 1, wherekis the number of survivors. - Each surviving node's parent value is rewritten using the new numbering.
- A surviving root still points to itself under the new numbering (
result[j] == j). - If no node survives, return an empty list.
A surviving node never has a removed parent, because a child of a removed node is itself removed.
Constraints
1 <= len(parents) <= 10^50 <= parents[i] < len(parents)0 <= target < len(parents)- The input is a valid forest: no cycles other than root self-loops.
- Very deep trees are possible, so avoid relying on deep recursion.
Examples
Example 1
Input: prune_branch([0, 0, 1, 1, 2], 1, False)
Output: [0, -1, -1, -1, -1]
Example 2
Input: prune_branch([0, 0, 2, 2, 3], 0, True)
Output: [0, 0, 1]
Hints
Hint 1
A parent array only lets you walk upward. Think about building a children list once so you can walk downward from the target. Remember not to list a root as its own child.
Hint 2
Collect the removed set with an iterative traversal (explicit stack) starting at target, marking each visited node so it is handled once.
Hint 3
For compact mode, scan nodes in increasing order and assign each survivor the next free new index. Then map each survivor's parent through that table; a surviving root maps to itself automatically.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A parent array only gives upward links, so the descendants of target cannot be listed directly. First invert the array: in one pass, append each non-root node to the children list of its parent (skipping self-loops so a root is never its own child).
Then run an iterative depth-first search from target, using an explicit stack and a removed flag per node. Every node reached is in the removed subtree.
Producing the output:
- Mark mode: copy
parentsand set-1at every removed index. - Compact mode: scan indices in ascending order, giving each survivor the next unused new index (
new_index[old] = new). Then, for each survivor in order, outputnew_index[parents[old]]. For a surviving root,parents[old] == old, so this yields its own new index.
Why it is correct
- A node is a descendant of
targetexactly when it is reachable fromtargetthrough child edges, which is what the DFS explores. Theremovedflag ensures each node is processed once. - A survivor's parent is never removed: otherwise the survivor would be a descendant of a removed node and would itself be removed. So
new_index[parent]is always a valid index, never-1. - Survivors are numbered in a single ascending scan, so the old-to-new mapping is strictly increasing and relative order is preserved.
- Surviving roots map to their own new index, so they stay self-referential.
Complexity
- Time: O(n), since building children, the DFS, and the output pass are each linear.
- Space: O(n) for the children lists, flags, stack, index map and output.
Reference solution
from typing import List
def prune_branch(parents: List[int], target: int, compact: bool = False) -> List[int]:
n = len(parents)
children = [[] for _ in range(n)]
for node, parent in enumerate(parents):
if node != parent:
children[parent].append(node)
removed = [False] * n
stack = [target]
while stack:
node = stack.pop()
if removed[node]:
continue
removed[node] = True
stack.extend(children[node])
if not compact:
result = parents[:]
for node in range(n):
if removed[node]:
result[node] = -1
return result
new_index = [-1] * n
survivors = []
for node in range(n):
if not removed[node]:
new_index[node] = len(survivors)
survivors.append(node)
result = []
for node in survivors:
parent = parents[node]
if parent == node:
result.append(new_index[node])
else:
result.append(new_index[parent])
return result