Prune and Reindex a Parent-Array Forest
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
An n-node forest is encoded in a zero-indexed integer array parents of length n, where parents[i] stores the parent index of node i. Within this array:
- Any root
rpoints to itself (parents[r] == r). - Apart from root self-links, no cycles exist — walking parent links from any node eventually reaches a root.
Given parents, an index target to prune, and a boolean compact (defaulting to False), remove target together with every node in target's subtree (its children, grandchildren, and all deeper descendants).
Implement delete_subtree(parents, target, compact=False) to support two output formats:
- Tombstone mode (
compact = False):- Return an array of the original length
n. - Write
-1attargetand at every descendant oftarget. - Leave every surviving node at its original index with its original parent value.
- Return an array of the original length
- Compaction mode (
compact = True):- Drop
targetand all of its descendants from the array. - Keep the
ksurviving nodes in their original left-to-right order, assigning them new indices0throughk - 1. - Translate every survivor's stored parent index to that parent's new index (surviving roots remain self-pointing at their new indices).
- Drop
Examples
Example 1
Input: parents = [0, 0, 0, 2, 3, 5], target = 2, compact = False
Output: [0, 0, -1, -1, -1, 5]
Root 0 has children 1 and 2; node 2 has child 3, which has child 4; and node 5 is a separate single-node root (parents[5] == 5). Pruning target = 2 removes {2, 3, 4}, replacing those three slots with -1 while {0, 1, 5} keep their original values.
Example 2
Input: parents = [0, 0, 1, 3, 3, 3], target = 1, compact = True
Output: [0, 1, 1, 1]
Pruning target = 1 removes {1, 2} from the first tree, leaving survivors {0, 3, 4, 5}. Renumbering them in order maps 0 -> 0, 3 -> 1, 4 -> 2, and 5 -> 3. Their old parent entries [0, 3, 3, 3] translate to [0, 1, 1, 1], with roots 0 and 1 each pointing to themselves.
Constraints
1 <= len(parents) <= 10^50 <= parents[i] < len(parents)for every0 <= i < len(parents)0 <= target < len(parents)- Every node's parent chain terminates at a self-pointing root.
Step-by-step walkthrough
Understand the parent-array forest and the two modes
A forest is a collection of one or more separate trees. Here, all
nnodes (0ton - 1) live inside a single listparents, whereparents[i]gives nodei's parent and every root points to itself (parents[r] == r):Example 2: parents = [0, 0, 1, 3, 3, 3] Tree A Tree B 0 3 (0 and 3 are roots: parents[0]=0, parents[3]=3) | / \ 1 4 5 | 2Pruning
targetremovestargetplus all of its descendants (children, grandchildren, and deeper levels). Depending oncompact, we return one of two formats:- Tombstoning (
compact = False): Keep lengthn, overwrite every deleted slot with-1, and leave surviving slots untouched. - Compacting (
compact = True): Drop deleted slots completely, renumber theksurvivors0, 1, ..., k - 1in their original left-to-right order, and translate each survivor's parent index to its parent's new index (surviving roots stay self-loopsresult[new_r] == new_r).
Watch two subtle details: a parent index can be larger than its child's index (such as
parents[0] = 2), and returning a fresh list avoids mutating the caller'sparentsarray.- Tombstoning (
Why walking upward from every node is too slow
Because
parentspoints upward, a tempting brute force tests each nodeifrom0ton - 1by climbingi -> parents[i] -> ...until reaching eithertarget(deletei) or a root (keepi).On a single chain of
n = 100,000nodes (0 <- 1 <- 2 <- ... <- 99,999), climbing upward from every node takes1 + 2 + ... + n ≈ n^2 / 2 = 5 * 10^9steps — far too slow! Every node belowtargetwastes work re-walking the same path. Instead of climbing up from allnnodes, we want to start attargetand walk down through its subtree once.Flip parent pointers into child lists and run iterative DFS
To traverse downward in
O(n)time, we first invertparentsinto an adjacency listchildren, wherechildren[u]holds all direct children ofu:parents = [0, 0, 0, 2, 3, 5] ---> children[0] = [1, 2] (skip 0 -> 0 self-loop!) children[1] = [] children[2] = [3] children[3] = [4] children[4] = [] children[5] = [] (skip 5 -> 5 self-loop!)Two details are essential here:
- Skip root self-loops (
parent != node): A root satisfiesparents[r] == r. Addingrtochildren[r]would make rootrlook like its own child and loop forever whentarget == r. - Use an explicit list
stackinstead of recursion: Python's call stack defaults to1,000frames, so recursive DFS raisesRecursionErroron a100,000-node chain. An explicit Python liststacklives on the heap and handles arbitrary depth safely.
from typing import Any, Dict, List, Optional, Set, Tuple def find_deleted_nodes(parents: list[int], target: int) -> list[bool]: """Return is_deleted[0..n-1], True for target and all of its descendants.""" n = len(parents) # children[u]: list of direct child indices whose parent is u (excluding self-loops). children = [] for _ in range(n): children.append([]) # Phase 1: Reverse parent pointers into downward child lists. for node in range(n): parent = parents[node] # Skip root self-loops (parents[root] == root); otherwise a root would look # like its own child and push itself onto the stack forever. if parent != node: children[parent].append(node) # Phase 2: Iterative DFS from target to mark its entire subtree. # Using an explicit list stack avoids RecursionError on 10^5-deep chains. is_deleted = [False] * n is_deleted[target] = True stack = [target] while stack: node = stack.pop() for child in children[node]: is_deleted[child] = True stack.append(child) return is_deleted- Skip root self-loops (
Mode 1: Tombstoning (compact = False)
Once
is_deletedis computed, tombstoning takes one linear pass: copyparentsintoresultand write-1whereveris_deleted[node]isTrue.Can a surviving node ever point to a
-1tombstone? Never! If a node's parent belonged totarget's subtree, then the node itself would also be a descendant oftargetand would already haveis_deleted[node] == True. Every survivor's parent is guaranteed to survive.is_deleted = find_deleted_nodes(parents, target) n = len(parents) # Mode 1 (Tombstoning): Keep length n, copy input so caller's list is untouched, # and overwrite deleted positions with -1. if not compact: result = list(parents) for node in range(n): if is_deleted[node]: result[node] = -1 return resultMode 2: Compacting (compact = True) in two clean passes
When
compact = True, we renumber survivors and translate their parent pointers in two separateO(n)passes:- Pass 1 (Build
old_to_new): Scannodefrom0ton - 1. Whenevernot is_deleted[node], setold_to_new[node] = next_new_indexand incrementnext_new_index. Scanning left to right preserves relative order and assigns0, 1, ..., k - 1. - Pass 2 (Translate parent pointers): Scan
nodefrom0ton - 1again. For each survivor, readold_parent = parents[node]and appendold_to_new[old_parent]toresult.
Why not merge Pass 1 and Pass 2 into a single loop? Because a child can sit to the left of its parent in the array (for example,
parents = [2, 1, 4, 3, 1], where node0's parent is node2). Atnode = 0during Pass 1,old_to_new[2]has not been assigned yet! Completing Pass 1 first guarantees every survivor's new ID is ready. Also notice that for any surviving rootr,parents[r] == r, soold_to_new[parents[r]]evaluates toold_to_new[r]— keeping roots self-referential automatically.old_to_new = [-1] * n next_new_index = 0 for node in range(n): if not is_deleted[node]: old_to_new[node] = next_new_index next_new_index += 1 result = [] for node in range(n): if not is_deleted[node]: old_parent = parents[node] result.append(old_to_new[old_parent])- Pass 1 (Build
Trace Example 2 step by step
Let's trace
parents = [0, 0, 1, 3, 3, 3],target = 1,compact = True:Index (old): 0 1 2 3 4 5 parents: [0, 0, 1, 3, 3, 3] 1. children: 0 -> [1], 1 -> [2], 2 -> [], 3 -> [4, 5], 4 -> [], 5 -> [] (roots 0 and 3 skip their self-loops) 2. DFS from 1: marks 1, then child 2 is_deleted: [False, True, True, False, False, False] 3. Pass 1 (old_to_new): old index: 0 1 2 3 4 5 old_to_new: [ 0, -1, -1, 1, 2, 3] 4. Pass 2 (remap survivors 0, 3, 4, 5): node 0: old_parent = 0 -> old_to_new[0] = 0 (stays a root at index 0) node 3: old_parent = 3 -> old_to_new[3] = 1 (root shifts to index 1 -> self-loop!) node 4: old_parent = 3 -> old_to_new[3] = 1 node 5: old_parent = 3 -> old_to_new[3] = 1 result = [0, 1, 1, 1]If
compact = Falseon the same input, Mode 1 overwrites indices1and2with-1, returning[0, -1, -1, 3, 3, 3].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def find_deleted_nodes(parents: list[int], target: int) -> list[bool]: """Return is_deleted[0..n-1], True for target and all of its descendants.""" n = len(parents) # children[u]: list of direct child indices whose parent is u (excluding self-loops). children = [] for _ in range(n): children.append([]) # Phase 1: Reverse parent pointers into downward child lists. for node in range(n): parent = parents[node] # Skip root self-loops (parents[root] == root); otherwise a root would look # like its own child and push itself onto the stack forever. if parent != node: children[parent].append(node) # Phase 2: Iterative DFS from target to mark its entire subtree. # Using an explicit list stack avoids RecursionError on 10^5-deep chains. is_deleted = [False] * n is_deleted[target] = True stack = [target] while stack: node = stack.pop() for child in children[node]: is_deleted[child] = True stack.append(child) return is_deleted def delete_subtree(parents: list[int], target: int, compact: bool = False) -> list[int]: is_deleted = find_deleted_nodes(parents, target) n = len(parents) # Mode 1 (Tombstoning): Keep length n, copy input so caller's list is untouched, # and overwrite deleted positions with -1. if not compact: result = list(parents) for node in range(n): if is_deleted[node]: result[node] = -1 return result # Mode 2 (Compacting), Pass 1: Assign sequential IDs 0..k-1 to survivors in order. # We must finish numbering ALL survivors before rewriting any parent pointer, # because a child can sit at a smaller index than its parent (e.g. parents[0] == 2). old_to_new = [-1] * n next_new_index = 0 for node in range(n): if not is_deleted[node]: old_to_new[node] = next_new_index next_new_index += 1 # Mode 2 (Compacting), Pass 2: Emit remapped parent pointers for every survivor. # Every survivor's parent also survived (otherwise the node would be in target's # subtree too), and roots (parents[r] == r) map cleanly to old_to_new[r] == new_r. result = [] for node in range(n): if not is_deleted[node]: old_parent = parents[node] result.append(old_to_new[old_parent]) return result✅ Submit now — all tests should pass.
Intuition & how it works
Think of parents as a company org-chart table where each row i only records that employee's direct manager parents[i] (and each CEO lists themselves). When the manager at row target leaves along with their entire department, we first build a "direct reports" directory — an adjacency list, which maps each node to a list of its immediate children — in one scan of the table. Next, we walk downward from target using Depth-First Search (DFS) — exploring target's children, grandchildren, and deeper descendants with an explicit stack — to flag everyone in that subtree (is_deleted). Depending on compact, we either overwrite flagged rows with -1 — a tombstone, meaning a sentinel value that marks a slot as deleted without shifting other indices — or assign the surviving employees sequential IDs 0 .. k - 1 (old_to_new) and translate each survivor's manager ID through that lookup table.
Why does the obvious upward-walk approach fail? Testing every node i by climbing i -> parents[i] -> ... up to target or a CEO works on shallow trees, but on a 100,000-person chain it repeats the same upward steps from every single row, costing roughly n^2 / 2 = 5 * 10^9 operations. Trying a single left-to-right pass (is_deleted[i] = is_deleted[parents[i]]) also breaks whenever a child has a smaller index than its parent (such as parents = [2, 1, 4, 3, 1]), because you visit the child before deciding whether its parent was deleted. Inverting parent pointers into child lists runs in O(n) time regardless of tree depth or index order.
Let's trace parents = [0, 0, 1, 3, 3, 3] with target = 1 in both modes:
Old index: 0 1 2 3 4 5
parents: [0, 0, 1, 3, 3, 3] Tree A: 0 -> 1 -> 2 Tree B: 3 -> {4, 5}
Step 1 (Child lists): 0:[1], 1:[2], 2:[], 3:[4, 5], 4:[], 5:[] (self-loops skipped)
Step 2 (DFS from 1): marks 1, then 2 -> is_deleted = [False, True, True, False, False, False]
Mode A (compact=False, Tombstoning):
Replace True slots with -1 -> [0, -1, -1, 3, 3, 3]
Mode B (compact=True, Compacting):
Pass 1: survivors 0, 3, 4, 5 get IDs -> old_to_new = [0, -1, -1, 1, 2, 3]
Pass 2: remap survivor parents 0,3,3,3 -> [old_to_new[0], old_to_new[3], old_to_new[3], old_to_new[3]]
-> [0, 1, 1, 1]
Complexity
Let n = len(parents) be the number of nodes in the forest.
- Time:
O(n). Reversingparentsintochildrenscans allnnodes once; the iterative DFS visits each node intarget's subtree at most once (at mostnpushes and pops); and tombstoning or two-pass compacting scans then-element arrays at most twice withO(1)array lookups per node. - Space:
O(n). Across allnlists inchildren, each non-root node appears once (<= nintegers total), andis_deleted,stack,old_to_new, andresulteach hold at mostnelements.
Edge cases
targetis a leaf node:children[target]is empty, so onlytargetis tombstoned or removed.targetis a root in a multi-tree forest: Its entire tree is deleted while all other trees survive (untouched under tombstoning, or shifted to lower indices with remapped self-loops under compacting).- Entire forest is deleted (
[0]withtarget = 0, or single tree pruned at root): Tombstoning returns[-1, ..., -1]; compacting returns an empty list[]. - Parent index larger than child index (
parents = [2, 1, 4, 3, 1],target = 4): Buildingchildrenworks in any index order, and completing Pass 1 (old_to_new) before Pass 2 ensuresold_to_new[parents[node]]is already populated even whenparents[node] > node. - Maximum chain depth (
n = 10^5): The explicitstacklist avoids Python's1,000-call recursion limit. - Input immutability: Copying
parentsin tombstoning mode leaves the caller's list untouched.
Common mistakes
- Including root self-loops (
parents[r] == r) inchildren: Ifris appended tochildren[r], deleting rootrwithout a separate visited check pushesrontostackendlessly. - Using recursive DFS: A valid chain of
100,000nodes crashes withRecursionErrorin Python. - Numbering survivors and rewriting parent pointers in a single pass: If
node = 0hasparents[0] = 2,old_to_new[2]is still-1when the loop is at index0, corruptingresult[0]into-1. Always completeold_to_newin Pass 1 before Pass 2. - Forgetting to remap surviving roots when compacting: In Example 2, root
3shifts to index1; leaving its entry as3instead of1breaks theparents[new_r] == new_rrule. Passing root pointers throughold_to_new[parents[node]]handles roots and non-roots uniformly. - Deleting only direct children (
parents[i] == target): Grandchildren and deeper levels must be deleted too (as in Example 1, where node4's parent is3, whose parent istarget = 2). - Assuming a subtree occupies contiguous array indices: Sibling subtrees can interleave arbitrarily in the array (e.g.,
parents = [0, 0, 0, 1, 2]).
Alternative approaches
- Upward walks with memoization: Memoization means caching each node's outcome (
deletedvssurvives) the first time you compute it so subsequent walks reuse it immediately. Climbing upward from each node until hittingtarget, a root, or an already-cached node — and then writing that result along every node on the climbed path — visits each edge at most twice (O(n)time) without allocatingchildren.
Follow-up questions
- How would you process a long sequence of delete operations efficiently without reconstructing the child lists from scratch each time? Build
childrenonce up front inO(n)time and maintainis_deletedacross calls while operating in tombstone mode so indices remain stable. On eachdelete(target), return immediately ifis_deleted[target]is alreadyTrue; otherwise run iterative DFS fromtargetand skip any child that already hasis_deleted[child] == True(its subtree was pruned earlier), bounding total DFS work across all deletions combined toO(n). Run compaction lazily — either only when exporting a snapshot or whenever tombstones exceed half the array, giving amortizedO(1)work per deleted node (occasionalO(n)compactions average out to constant cost per pruned node). - If you are allowed to modify the input array in place, how can you mark the target subtree in O(n) time using O(1) extra memory? Use memoized upward climbs and encode each node's status directly inside
parents[i]with negative numbers so no auxiliary array is needed. First setparents[target] = -1(deleted). Then for eachstartfrom0ton - 1, climb upward whileparents[node] >= 0 and parents[node] != nodeto see whether the chain ends at-1(deleted) or at a root / encoded survivor, and climb the same chain a second time setting each node to-1if deleted or-(original_parent + 2)if surviving (always<= -2, never colliding with-1or unvisited>= 0pointers). Every node is decided once (O(n)time,O(1)extra variables), and one final scan decodes-(p + 2)back top = -parents[i] - 2for tombstoning; compacting still needsO(n)space whenparents[i] > i, orO(1)space in place ifparents[i] <= ialways holds. - What changes are needed if the parent array might contain non-root cycles or out-of-range pointers? Clarify the desired contract first: either validate and reject malformed graphs up front, or prune every node reachable downward from
target. You can detect non-root cycles and out-of-bounds chains inO(n)time by climbing from each node with 3-state coloring (0= unvisited,1= on current walk,2= verified): meeting state1atparents[u] != uproves a cycle, and< 0or>= npointers flag broken chains. If downward pruning is still desired on cyclic graphs, guard the DFS push infind_deleted_nodeswithif not is_deleted[child]:so no node entersstackmore than once.
Follow-up questions
- How would you process a long sequence of delete operations efficiently without reconstructing the child lists from scratch each time?
- If you are allowed to modify the input array in place, how can you mark the target subtree in O(n) time using O(1) extra memory?
- What changes are needed if the parent array might contain non-root cycles or out-of-range pointers?
Similar questions
- Time-Indexed Moderation Log Queries
- Masonry Column Height Allocation
- Percentile Bootstrap Interval for Mean Order Amount
- Unique Pin Traversal Over Linked Boards
- Mean Distinct Saved Pins Across Users
- Count Reachable Tiles Within Step Limit
More Pinterest interview questions
- Minimum Boardings on Circular Bus Routes Medium
- Time-Indexed Moderation Log Queries Medium
- Confusion Matrix Metrics and ML Foundations Hard Pro
- Multi-Topic Behavioral Onsite: Metrics, Leadership, Team Dynamics, and Conflict Hard Pro
- Seven-Day Highly Active User Share by Country Medium Pro
- Bootstrap Aggregating Classifier Over Decision Trees Hard Pro
- Closest Qualifying Elevator Medium Pro
- Balance Group IOUs with Fewer Transfers Medium Pro
- Clearing Shared Expenses in Minimal Transfers Medium Pro
- Minimum-Transfer Ledger Settlement Medium Pro