Fewest Node Removals to Cap Tree Height

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given an N-ary tree of n nodes rooted at node 0 together with a target height limit k, determine the fewest non-root nodes you must splice out so the resulting tree's height does not exceed k:

def min_deletions_for_height(parent: list[int], k: int) -> int:
  • Tree encoding: Nodes are numbered 0 through n - 1. Node 0 is the root (parent[0] == -1), and for every 1 <= i < n, parent[i] gives the parent index of node i. Note that parent[i] may be larger than i.
  • Splicing rule: Root 0 may never be removed, while any node in 1 .. n - 1 may be removed. Removing a node does not discard its subtree—instead, all of its direct children re-attach to its parent (and if multiple consecutive ancestors are removed, children attach to their closest surviving ancestor).
  • Height convention: Height equals the number of nodes along the longest downward path starting at root 0. A tree consisting solely of root 0 therefore has height 1.
  • Return value: Return only the minimum number of removed nodes needed to achieve height <= k (multiple distinct node sets may tie for this minimum).

Examples

Example 1

parent = [-1, 0, 0, 1, 2, 2, 4, 6]

        0
       / \
      1   2
      |  / \
      3 4   5
        |
        6
        |
        7

Input:  parent = [-1, 0, 0, 1, 2, 2, 4, 6], k = 3
Output: 2

The longest path 0 -> 2 -> 4 -> 6 -> 7 contains 5 nodes (height 5), while 0 -> 1 -> 3 already has height 3. Splicing out two nodes from {2, 4, 6, 7} (for example nodes 2 and 4, promoting 5 and 6 directly under root 0) brings every root-to-leaf path within 3 nodes. One removal cannot shrink a 5-node path down to 3 nodes.

Example 2

Input:  parent = [-1, 0, 0, 1, 2, 2, 4, 6], k = 2
Output: 4

On the same tree with k = 2, the left branch 0 -> 1 -> 3 requires removing at least one of {1, 3}, and the right path 0 -> 2 -> 4 -> 6 -> 7 requires removing at least three of {2, 4, 6, 7}. Because those two sets are disjoint, at least 1 + 3 = 4 removals are needed; removing {1, 2, 4, 6} attaches 3, 5, and 7 directly under root 0 (height 2).

Example 3

parent = [-1, 4, 4, 4, 0, 1]

          0
          |
          4
        / | \
       1  2  3
       |
       5

Input:  parent = [-1, 4, 4, 4, 0, 1], k = 2
Output: 2

Splicing out shared ancestors 4 and 1 attaches 5, 2, and 3 directly to root 0, achieving height 2 in 2 removals (whereas removing deepest leaves from the bottom would require 4 removals). Notice also that node 4 is the parent of lower-numbered nodes 1, 2, and 3.

Constraints

  • 1 <= n == len(parent) <= 10^5
  • parent[0] == -1, and 0 <= parent[i] <= n - 1 for all 1 <= i < n; parent pointers form a single valid tree rooted at 0 with no cycles
  • 1 <= k <= n (splicing out every non-root node leaves height 1, so a valid solution always exists)
  • Tree depth may be up to n (such as a single chain)

Step-by-step walkthrough

  1. Understand what splicing out a node does to tree height

    We are given an n-node tree rooted at 0 (parent[0] == -1). When we remove a non-root node, it is spliced out: its children are not discarded, they simply re-attach to its nearest surviving ancestor. Height is measured as the number of nodes along the longest root-to-leaf path (so root 0 alone has height 1).

    Look at Example 3 (parent = [-1, 4, 4, 4, 0, 1], k = 2):

    Original tree (height = 4):          After splicing out nodes 4 and 1 (height = 2):
              0                                        0
              |                                      / | \
              4   <-- remove                        5  2  3
            / | \
           1  2  3  <-- remove 1
           |
           5
    

    Notice what happens to any surviving node v: its surviving ancestors stay in the exact same top-to-bottom order, while removed ancestors vanish from the path. That gives a clean invariant:

    new depth of a kept node v = number of kept nodes on the original path from root 0 down to v
    

    Because root 0 can never be removed, keeping the resulting tree's height at most k is equivalent to ensuring every original root-to-leaf path keeps at most k - 1 non-root nodes! Removing as few nodes as possible means keeping as many non-root nodes as possible under that k - 1 per-path budget.

  2. Why brute force and "delete deepest first" fail

    Two intuitive ideas break down quickly:

    • Trying every subset of non-root nodes checks up to 2^(n - 1) subsets — fine for 8 nodes in a unit test, impossible for n = 100,000.
    • Greedily removing the deepest leaves first wastes removals. Look again at Example 3 above with k = 2. If you remove the deepest node 5 first (depth 4), nodes 1, 2, and 3 still sit at depth 3 on three separate branches, forcing you to remove all three of them too (4 removals total)! Splicing out nodes 4 and 1 higher up shortens every branch below them at once in just 2 removals.

    High nodes sit on many root-to-leaf paths, whereas low nodes near the leaves sit on very few. That suggests we should keep nodes near the bottom and remove nodes that sit too high above leaves.

  3. Key idea: measure height from the bottom up

    To measure how high a node sits above the leaves below it, define subtree_height[v] as the number of nodes on the longest downward path starting at v:

    • Every leaf has subtree_height = 1 (just itself).
    • Any internal node v has subtree_height[v] = 1 + max(subtree_height[c] for each child c).

    Our rule is remarkably direct: keep every non-root node with subtree_height[v] <= k - 1, and delete every non-root node with subtree_height[v] >= k.

    First verify why this choice always produces height at most k: - Stepping from any parent down to a child strictly decreases subtree_height by at least 1 (since subtree_height[parent] >= subtree_height[child] + 1). - Consequently, along any single root-to-leaf path, the kept non-root nodes must all have distinct integer heights chosen from {1, 2, ..., k - 1}. - Because {1, 2, ..., k - 1} contains only k - 1 values, at most k - 1 non-root nodes survive on any path! Including root 0 gives at most k nodes on every path.

  4. Why no valid choice can remove fewer nodes

    How do we know for sure that no cleverer set of removals could delete fewer nodes? Partition all non-root nodes into disjoint vertical chains by linking each non-leaf node to one of its tallest children (a child with subtree_height == subtree_height[v] - 1):

    Example 3 split into disjoint chains of non-root nodes (k = 2, so max 1 kept per path):
    
      Chain A (length 3):  4 (h=3) ==> 1 (h=2) ==> 5 (h=1)   -> on one path: at most 1 can stay, >= 2 removed!
      Chain B (length 1):  2 (h=1)                           -> at most 1 can stay, >= 0 removed
      Chain C (length 1):  3 (h=1)                           -> at most 1 can stay, >= 0 removed
    

    Look at what happens on every chain:

    1. Because each node selects at most one child and has only one parent, these chains never share a node and cover every non-root node in the tree.
    2. Along a chain of length L, the heights count down L, L - 1, ..., 2, 1, and all L nodes lie on a single root-to-leaf path.
    3. Because any valid solution can keep at most k - 1 non-root nodes on a single root-to-leaf path, any valid solution is forced to remove at least max(0, L - (k - 1)) nodes from that chain — which equals the exact number of nodes on that chain with subtree_height >= k!

    Summing those forced removals across all disjoint chains proves every valid solution must remove at least as many nodes as our subtree_height[v] >= k count. Our rule hits that lower bound exactly, so it is guaranteed optimal!

  5. Phase 1: build a top-down order without recursion

    To compute subtree_height from leaves up to the root, we must avoid two traps from the constraints:

    • Parent indices can exceed child indices (as in Example 3 where node 4 is the parent of 1, 2, and 3), so looping node = n - 1 down to 1 can visit a parent before its children.
    • Depth can reach 100,000 (a single long chain), so recursive depth-first search exceeds Python's 1,000-call recursion limit.

    Instead, we build children lists and collect a breadth-first order bfs_order starting at root 0. Because every child is appended when its parent is processed, every parent precedes all of its children in bfs_order — meaning reversed(bfs_order) visits every child before its parent!

        n = len(parent)
    
        # children[u]: list of direct child nodes of node u, e.g. [[4], [5], [], [], [1, 2, 3], []].
        children: list[list[int]] = [[] for _ in range(n)]
        for node in range(1, n):
            children[parent[node]].append(node)
    
        # Phase 1: Build a top-down breadth-first order starting from root 0.
        bfs_order = [0]
        read_idx = 0
        while read_idx < len(bfs_order):
            current = bfs_order[read_idx]
            for child in children[current]:
                bfs_order.append(child)
            read_idx += 1
    
  6. Phase 2 & 3: compute bottom-up heights and count removals

    Walking reversed(bfs_order) guarantees that when we visit node, every descendant of node has already propagated its height into subtree_height[node]. We then propagate subtree_height[node] + 1 up to parent[node].

    Finally, we scan non-root nodes 1 .. n - 1 (skipping 0, because root 0 cannot be deleted) and count how many satisfy subtree_height[node] >= k. Watch the boundary >= k: if subtree_height[node] == k, keeping node plus k - 1 descendants below it plus root 0 above it would produce a path of k + 1 nodes, which is 1 too tall!

        subtree_height = [1] * n
    
        # Phase 2: Walk bfs_order in reverse (bottom-up from leaves to root).
        for node in reversed(bfs_order):
            if node != 0:
                up = parent[node]
                candidate_height = subtree_height[node] + 1
                if candidate_height > subtree_height[up]:
                    subtree_height[up] = candidate_height
    
        # Phase 3: Delete every non-root node whose subtree_height is at least k.
        deletions = 0
        for node in range(1, n):
            if subtree_height[node] >= k:
                deletions += 1
    
  7. Trace Example 3 step by step

    Let's trace parent = [-1, 4, 4, 4, 0, 1] and k = 2:

    children  = [[4], [5], [], [], [1, 2, 3], []]
    bfs_order = [0, 4, 1, 2, 3, 5]
    reversed  = [5, 3, 2, 1, 4, 0]
    
    Bottom-up subtree_height updates (starts at [1, 1, 1, 1, 1, 1]):
      node 5 (height 1) -> parent 1 becomes max(1, 1 + 1) = 2
      node 3 (height 1) -> parent 4 becomes max(1, 1 + 1) = 2
      node 2 (height 1) -> parent 4 stays   max(2, 1 + 1) = 2
      node 1 (height 2) -> parent 4 becomes max(2, 2 + 1) = 3
      node 4 (height 3) -> parent 0 becomes max(1, 3 + 1) = 4
    
    Final subtree_height = [4, 2, 1, 1, 3, 1]
    
    Check non-root nodes 1..5 against k = 2 (delete if subtree_height >= 2):
      node 1: height 2 >= 2 -> DELETE
      node 2: height 1 <  2 -> keep
      node 3: height 1 <  2 -> keep
      node 4: height 3 >= 2 -> DELETE
      node 5: height 1 <  2 -> keep
    Total deletions = 2
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def min_deletions_for_height(parent: list[int], k: int) -> int:
        n = len(parent)
    
        # children[u]: list of direct child nodes of node u, e.g. [[4], [5], [], [], [1, 2, 3], []].
        children: list[list[int]] = [[] for _ in range(n)]
        for node in range(1, n):
            children[parent[node]].append(node)
    
        # Phase 1: Build a top-down breadth-first order starting from root 0.
        # We cannot rely on index order 0..n-1 because a parent can have a larger index than its child,
        # and we avoid recursion because a chain of 10^5 nodes would exceed Python's recursion limit.
        bfs_order = [0]
        read_idx = 0
        while read_idx < len(bfs_order):
            current = bfs_order[read_idx]
            for child in children[current]:
                bfs_order.append(child)
            read_idx += 1
    
        # subtree_height[v]: number of nodes on the longest downward path starting at v (a leaf has height 1).
        subtree_height = [1] * n
    
        # Phase 2: Walk bfs_order in reverse (bottom-up from leaves to root) so every child's height is final
        # before it updates its parent's height.
        for node in reversed(bfs_order):
            if node != 0:
                up = parent[node]
                candidate_height = subtree_height[node] + 1
                if candidate_height > subtree_height[up]:
                    subtree_height[up] = candidate_height
    
        # Phase 3: The root (node 0) is always kept, leaving room for at most k - 1 kept non-root nodes on any
        # downward path. Keep non-root nodes with subtree_height <= k - 1 and delete those with >= k.
        deletions = 0
        for node in range(1, n):
            if subtree_height[node] >= k:
                deletions += 1
        return deletions
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of flattening a company org chart where the CEO (root 0) cannot be removed, and whenever you remove a middle manager, all of their direct reports move up to report to the manager above them. If your goal is to limit the org chart to at most k levels, removing an individual contributor at the very bottom only shortens a single reporting line, whereas removing a middle manager higher up shortens every reporting line beneath them at once! Because root 0 always stays, keeping the tree height at most k means keeping at most k - 1 non-root people along any root-to-leaf line. Measuring each node's subtree height — the number of nodes on the longest downward path starting at that node (so leaves have height 1) — tells us exactly who to keep: keep every non-root node with subtree_height <= k - 1, and splice out every non-root node with subtree_height >= k.

Why do the obvious approaches fail? Checking every subset of removed nodes examines 2^(n - 1) subsets, which is astronomical for n = 100,000. Meanwhile, greedily removing the deepest leaves from the bottom up gets trapped whenever a tree branches: in Example 3 (0 -> 4 -> {1 -> 5, 2, 3}, k = 2), removing leaf 5 still leaves 1, 2, and 3 all too deep, costing 4 removals instead of splicing out 4 and 1 (2 removals). By contrast, our bottom-up height rule is provably optimal because partitioning non-root nodes into disjoint tallest-child chains shows every chain of length L lies on a single root-to-leaf path and must lose at least max(0, L - (k - 1)) nodes — the exact count of nodes with subtree_height >= k.

Walk through Example 3 (parent = [-1, 4, 4, 4, 0, 1], k = 2): 1. Build a top-down breadth-first search (BFS) order — visiting nodes level by level from root 0 with a queue — giving [0, 4, 1, 2, 3, 5]. 2. Reverse that order ([5, 3, 2, 1, 4, 0]) to compute subtree_height from leaves up: leaves 5, 2, 3 have height 1; node 1 (parent of 5) gets 2; node 4 (parent of 1, 2, 3) gets 3; root 0 gets 4. 3. Count non-root nodes (1 .. 5) with subtree_height >= 2: nodes 1 (height 2) and 4 (height 3) qualify, while 2, 3, 5 (height 1) stay, returning 2.

Complexity

Let n = len(parent) be the number of nodes in the tree.

  • Time: O(n). Building the children adjacency lists scans n - 1 nodes once; building bfs_order appends and reads each of the n nodes once; the reversed height pass performs O(1) work per node; and the final loop checks n - 1 non-root nodes once.
  • Space: O(n). Storing children (with n - 1 total child entries), bfs_order (n ints), and subtree_height (n ints) all use linear memory, with zero recursion stack overhead.

Edge cases

  • Single-node tree (parent = [-1], k = 1): The loop range(1, n) is empty, returning 0 removals (root alone already has height 1).
  • k = 1 on a larger tree: Every non-root node has subtree_height >= 1 == k, so all n - 1 non-root nodes are spliced out, leaving only root 0 (height 1).
  • Tree already within height k: Every non-root node has subtree_height <= tree_height - 1 < k, so 0 nodes are removed.
  • Single long path of n nodes: Non-root nodes have heights n - 1, n - 2, ..., 1, so n - k nodes have height >= k, returning n - k.
  • Parent index larger than child index (such as 4 parenting 1, 2, 3 in Example 3): bfs_order follows actual parent-child links rather than node numbers, computing heights in the right order.
  • Deep chain at n = 100,000: Iterative BFS order + reversed loop avoids Python's RecursionError.

Common mistakes

  • Removing the deepest nodes first (greedy by depth from root). Deep leaves sit on only one path each; splicing out shared ancestors higher up shortens many paths simultaneously (Example 3: 2 removals vs 4).
  • Filtering by depth from the root instead of height from the leaves. Whether a node can survive depends on how tall a chain hangs below it: in Example 3, node 4 sits at depth 2 (<= k), yet keeping it forces you to remove all three branches below it.
  • Off-by-one on the comparison (> k instead of >= k). Because root 0 is always kept and counts toward height, a non-root node with subtree_height == k would form a path of 1 + k nodes if all k levels from it downward were kept, so == k must be removed too.
  • Accidentally counting root 0 (range(n) instead of range(1, n)). Root 0 has subtree_height >= k whenever the initial tree is too tall, and the rules forbid removing the root.
  • Looping range(n - 1, 0, -1) assuming parent[i] < i. Parent indices may exceed child indices, so numerical index order is not topological.
  • Computing subtree_height with recursive DFS. A 100,000-node chain exceeds Python's default recursion limit of 1,000.

Alternative approaches

  • Bottom-up tree dynamic programming with a height budget: Define max_kept[v][b] as the maximum number of nodes you can keep inside v's subtree when at most b nodes may be kept along any downward path starting at v. Either remove v (sum(max_kept[c][b] for c in children[v])) or keep v when b >= 1 (1 + sum(max_kept[c][b - 1] for c in children[v])). While general, this takes O(n * k) time and space — up to 10^10 operations when n = k = 100,000 — whereas the unweighted height threshold runs in O(n).

Follow-up questions

  • How would you return one valid minimum-size list of deleted node IDs instead of just the deletion count? Collect [node for node in range(1, n) if subtree_height[node] >= k] in Phase 3 instead of incrementing a counter! That exact list is guaranteed to be a valid minimum-cardinality removal set (even when alternative tied sets exist, such as removing {4, 6} instead of {2, 4} in Example 1), and runs in O(n) time and space.
  • Suppose the tree is fixed and you must answer Q separate height-cap queries k_1, ..., k_Q—how fast can each query run? Notice that subtree_height[v] does not depend on k! Precompute subtree_height once in O(n), tally how many non-root nodes have each height h in a frequency table freq[1..n], and build a suffix sum array — where suffix[k] stores freq[k] + freq[k + 1] + ... + freq[n] — in one backward pass from n down to 1. Each query k then answers in O(1) time via suffix[k], yielding O(n + Q) total runtime.
  • How does the algorithm change if each non-root node i carries a positive removal cost cost[i] and you want the cheapest valid set of removals? With non-uniform weights, removing one expensive ancestor can cost more than removing several inexpensive leaves beneath it, so the unweighted subtree_height >= k threshold no longer suffices. Instead, evaluate the bottom-up budget DP max_saved[v][b] (maximum weight of kept nodes in v's subtree given path budget b), taking max(sum(max_saved[c][b]), cost[v] + sum(max_saved[c][b - 1])) along reversed(bfs_order) in O(n * min(k, tree_height)) time, and subtract the root's children's sum(max_saved[c][k - 1]) from sum(cost[1:]).

Follow-up questions

Similar questions

More Snowflake interview questions

All 130 Snowflake questions →