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 r points 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:

  1. Tombstone mode (compact = False):
    • Return an array of the original length n.
    • Write -1 at target and at every descendant of target.
    • Leave every surviving node at its original index with its original parent value.
  2. Compaction mode (compact = True):
    • Drop target and all of its descendants from the array.
    • Keep the k surviving nodes in their original left-to-right order, assigning them new indices 0 through k - 1.
    • Translate every survivor's stored parent index to that parent's new index (surviving roots remain self-pointing at their new indices).

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^5
  • 0 <= parents[i] < len(parents) for every 0 <= i < len(parents)
  • 0 <= target < len(parents)
  • Every node's parent chain terminates at a self-pointing root.

Step-by-step walkthrough

  1. Understand the parent-array forest and the two modes

    A forest is a collection of one or more separate trees. Here, all n nodes (0 to n - 1) live inside a single list parents, where parents[i] gives node i'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
         |
         2
    

    Pruning target removes target plus all of its descendants (children, grandchildren, and deeper levels). Depending on compact, we return one of two formats:

    1. Tombstoning (compact = False): Keep length n, overwrite every deleted slot with -1, and leave surviving slots untouched.
    2. Compacting (compact = True): Drop deleted slots completely, renumber the k survivors 0, 1, ..., k - 1 in their original left-to-right order, and translate each survivor's parent index to its parent's new index (surviving roots stay self-loops result[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's parents array.

  2. Why walking upward from every node is too slow

    Because parents points upward, a tempting brute force tests each node i from 0 to n - 1 by climbing i -> parents[i] -> ... until reaching either target (delete i) or a root (keep i).

    On a single chain of n = 100,000 nodes (0 <- 1 <- 2 <- ... <- 99,999), climbing upward from every node takes 1 + 2 + ... + n ≈ n^2 / 2 = 5 * 10^9 steps — far too slow! Every node below target wastes work re-walking the same path. Instead of climbing up from all n nodes, we want to start at target and walk down through its subtree once.

  3. Flip parent pointers into child lists and run iterative DFS

    To traverse downward in O(n) time, we first invert parents into an adjacency list children, where children[u] holds all direct children of u:

    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:

    1. Skip root self-loops (parent != node): A root satisfies parents[r] == r. Adding r to children[r] would make root r look like its own child and loop forever when target == r.
    2. Use an explicit list stack instead of recursion: Python's call stack defaults to 1,000 frames, so recursive DFS raises RecursionError on a 100,000-node chain. An explicit Python list stack lives 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
    
  4. Mode 1: Tombstoning (compact = False)

    Once is_deleted is computed, tombstoning takes one linear pass: copy parents into result and write -1 wherever is_deleted[node] is True.

    Can a surviving node ever point to a -1 tombstone? Never! If a node's parent belonged to target's subtree, then the node itself would also be a descendant of target and would already have is_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 result
    
  5. Mode 2: Compacting (compact = True) in two clean passes

    When compact = True, we renumber survivors and translate their parent pointers in two separate O(n) passes:

    • Pass 1 (Build old_to_new): Scan node from 0 to n - 1. Whenever not is_deleted[node], set old_to_new[node] = next_new_index and increment next_new_index. Scanning left to right preserves relative order and assigns 0, 1, ..., k - 1.
    • Pass 2 (Translate parent pointers): Scan node from 0 to n - 1 again. For each survivor, read old_parent = parents[node] and append old_to_new[old_parent] to result.

    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 node 0's parent is node 2). At node = 0 during 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 root r, parents[r] == r, so old_to_new[parents[r]] evaluates to old_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])
    
  6. 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 = False on the same input, Mode 1 overwrites indices 1 and 2 with -1, returning [0, -1, -1, 3, 3, 3].

  7. 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). Reversing parents into children scans all n nodes once; the iterative DFS visits each node in target's subtree at most once (at most n pushes and pops); and tombstoning or two-pass compacting scans the n-element arrays at most twice with O(1) array lookups per node.
  • Space: O(n). Across all n lists in children, each non-root node appears once (<= n integers total), and is_deleted, stack, old_to_new, and result each hold at most n elements.

Edge cases

  • target is a leaf node: children[target] is empty, so only target is tombstoned or removed.
  • target is 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] with target = 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): Building children works in any index order, and completing Pass 1 (old_to_new) before Pass 2 ensures old_to_new[parents[node]] is already populated even when parents[node] > node.
  • Maximum chain depth (n = 10^5): The explicit stack list avoids Python's 1,000-call recursion limit.
  • Input immutability: Copying parents in tombstoning mode leaves the caller's list untouched.

Common mistakes

  • Including root self-loops (parents[r] == r) in children: If r is appended to children[r], deleting root r without a separate visited check pushes r onto stack endlessly.
  • Using recursive DFS: A valid chain of 100,000 nodes crashes with RecursionError in Python.
  • Numbering survivors and rewriting parent pointers in a single pass: If node = 0 has parents[0] = 2, old_to_new[2] is still -1 when the loop is at index 0, corrupting result[0] into -1. Always complete old_to_new in Pass 1 before Pass 2.
  • Forgetting to remap surviving roots when compacting: In Example 2, root 3 shifts to index 1; leaving its entry as 3 instead of 1 breaks the parents[new_r] == new_r rule. Passing root pointers through old_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 node 4's parent is 3, whose parent is target = 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 (deleted vs survives) the first time you compute it so subsequent walks reuse it immediately. Climbing upward from each node until hitting target, 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 allocating children.

Follow-up questions

  • How would you process a long sequence of delete operations efficiently without reconstructing the child lists from scratch each time? Build children once up front in O(n) time and maintain is_deleted across calls while operating in tombstone mode so indices remain stable. On each delete(target), return immediately if is_deleted[target] is already True; otherwise run iterative DFS from target and skip any child that already has is_deleted[child] == True (its subtree was pruned earlier), bounding total DFS work across all deletions combined to O(n). Run compaction lazily — either only when exporting a snapshot or whenever tombstones exceed half the array, giving amortized O(1) work per deleted node (occasional O(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 set parents[target] = -1 (deleted). Then for each start from 0 to n - 1, climb upward while parents[node] >= 0 and parents[node] != node to 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 -1 if deleted or -(original_parent + 2) if surviving (always <= -2, never colliding with -1 or unvisited >= 0 pointers). Every node is decided once (O(n) time, O(1) extra variables), and one final scan decodes -(p + 2) back to p = -parents[i] - 2 for tombstoning; compacting still needs O(n) space when parents[i] > i, or O(1) space in place if parents[i] <= i always 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 in O(n) time by climbing from each node with 3-state coloring (0 = unvisited, 1 = on current walk, 2 = verified): meeting state 1 at parents[u] != u proves a cycle, and < 0 or >= n pointers flag broken chains. If downward pruning is still desired on cyclic graphs, guard the DFS push in find_deleted_nodes with if not is_deleted[child]: so no node enters stack more than once.

Follow-up questions

Similar questions

More Pinterest interview questions

All 161 Pinterest questions →