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
0throughn - 1. Node0is the root (parent[0] == -1), and for every1 <= i < n,parent[i]gives the parent index of nodei. Note thatparent[i]may be larger thani. - Splicing rule: Root
0may never be removed, while any node in1 .. n - 1may 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 root0therefore has height1. - 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^5parent[0] == -1, and0 <= parent[i] <= n - 1for all1 <= i < n; parent pointers form a single valid tree rooted at0with no cycles1 <= k <= n(splicing out every non-root node leaves height1, so a valid solution always exists)- Tree depth may be up to
n(such as a single chain)
Step-by-step walkthrough
Understand what splicing out a node does to tree height
We are given an
n-node tree rooted at0(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 root0alone has height1).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 | 5Notice 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 vBecause root
0can never be removed, keeping the resulting tree's height at mostkis equivalent to ensuring every original root-to-leaf path keeps at mostk - 1non-root nodes! Removing as few nodes as possible means keeping as many non-root nodes as possible under thatk - 1per-path budget.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 for8nodes in a unit test, impossible forn = 100,000. - Greedily removing the deepest leaves first wastes removals. Look again at Example 3 above with
k = 2. If you remove the deepest node5first (depth4), nodes1,2, and3still sit at depth3on three separate branches, forcing you to remove all three of them too (4removals total)! Splicing out nodes4and1higher up shortens every branch below them at once in just2removals.
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.
- Trying every subset of non-root nodes checks up to
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 atv:- Every leaf has
subtree_height = 1(just itself). - Any internal node
vhassubtree_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 withsubtree_height[v] >= k.First verify why this choice always produces height at most
k: - Stepping from any parent down to a child strictly decreasessubtree_heightby at least1(sincesubtree_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 onlyk - 1values, at mostk - 1non-root nodes survive on any path! Including root0gives at mostknodes on every path.- Every leaf has
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 removedLook at what happens on every chain:
- 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.
- Along a chain of length
L, the heights count downL, L - 1, ..., 2, 1, and allLnodes lie on a single root-to-leaf path. - Because any valid solution can keep at most
k - 1non-root nodes on a single root-to-leaf path, any valid solution is forced to remove at leastmax(0, L - (k - 1))nodes from that chain — which equals the exact number of nodes on that chain withsubtree_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] >= kcount. Our rule hits that lower bound exactly, so it is guaranteed optimal!Phase 1: build a top-down order without recursion
To compute
subtree_heightfrom 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
4is the parent of1,2, and3), so loopingnode = n - 1down to1can visit a parent before its children. - Depth can reach
100,000(a single long chain), so recursive depth-first search exceeds Python's1,000-call recursion limit.
Instead, we build
childrenlists and collect a breadth-first orderbfs_orderstarting at root0. Because every child is appended when its parent is processed, every parent precedes all of its children inbfs_order— meaningreversed(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- Parent indices can exceed child indices (as in Example 3 where node
Phase 2 & 3: compute bottom-up heights and count removals
Walking
reversed(bfs_order)guarantees that when we visitnode, every descendant ofnodehas already propagated its height intosubtree_height[node]. We then propagatesubtree_height[node] + 1up toparent[node].Finally, we scan non-root nodes
1 .. n - 1(skipping0, because root0cannot be deleted) and count how many satisfysubtree_height[node] >= k. Watch the boundary>= k: ifsubtree_height[node] == k, keepingnodeplusk - 1descendants below it plus root0above it would produce a path ofk + 1nodes, which is1too 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 += 1Trace Example 3 step by step
Let's trace
parent = [-1, 4, 4, 4, 0, 1]andk = 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 = 2Complete 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
childrenadjacency lists scansn - 1nodes once; buildingbfs_orderappends and reads each of thennodes once; the reversed height pass performs O(1) work per node; and the final loop checksn - 1non-root nodes once. - Space: O(n). Storing
children(withn - 1total child entries),bfs_order(nints), andsubtree_height(nints) all use linear memory, with zero recursion stack overhead.
Edge cases
- Single-node tree (
parent = [-1],k = 1): The looprange(1, n)is empty, returning0removals (root alone already has height1). k = 1on a larger tree: Every non-root node hassubtree_height >= 1 == k, so alln - 1non-root nodes are spliced out, leaving only root0(height1).- Tree already within height
k: Every non-root node hassubtree_height <= tree_height - 1 < k, so0nodes are removed. - Single long path of
nnodes: Non-root nodes have heightsn - 1, n - 2, ..., 1, son - knodes have height>= k, returningn - k. - Parent index larger than child index (such as
4parenting1, 2, 3in Example 3):bfs_orderfollows 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'sRecursionError.
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:
2removals vs4). - 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
4sits at depth2(<= k), yet keeping it forces you to remove all three branches below it. - Off-by-one on the comparison (
> kinstead of>= k). Because root0is always kept and counts toward height, a non-root node withsubtree_height == kwould form a path of1 + knodes if allklevels from it downward were kept, so== kmust be removed too. - Accidentally counting root
0(range(n)instead ofrange(1, n)). Root0hassubtree_height >= kwhenever the initial tree is too tall, and the rules forbid removing the root. - Looping
range(n - 1, 0, -1)assumingparent[i] < i. Parent indices may exceed child indices, so numerical index order is not topological. - Computing
subtree_heightwith recursive DFS. A100,000-node chain exceeds Python's default recursion limit of1,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 insidev's subtree when at mostbnodes may be kept along any downward path starting atv. Either removev(sum(max_kept[c][b] for c in children[v])) or keepvwhenb >= 1(1 + sum(max_kept[c][b - 1] for c in children[v])). While general, this takes O(n * k) time and space — up to10^10operations whenn = 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 onk! Precomputesubtree_heightonce in O(n), tally how many non-root nodes have each heighthin a frequency tablefreq[1..n], and build a suffix sum array — wheresuffix[k]storesfreq[k] + freq[k + 1] + ... + freq[n]— in one backward pass fromndown to1. Each querykthen answers in O(1) time viasuffix[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 >= kthreshold no longer suffices. Instead, evaluate the bottom-up budget DPmax_saved[v][b](maximum weight of kept nodes inv's subtree given path budgetb), takingmax(sum(max_saved[c][b]), cost[v] + sum(max_saved[c][b - 1]))alongreversed(bfs_order)in O(n * min(k, tree_height)) time, and subtract the root's children'ssum(max_saved[c][k - 1])fromsum(cost[1:]).
Follow-up questions
- How would you return one valid minimum-size list of deleted node IDs instead of just the deletion count?
- Suppose the tree is fixed and you must answer Q separate height-cap queries k_1, ..., k_Q—how fast can each query run?
- 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?
Similar questions
- Memoized First-Occurrence Binary Search
- Match Every Person to the Closest Cake Index
- Preorder Org-Chart Listing from Direct-Report Pairs
- Compute Subtree Value Totals Across a Parent-Array Tree
- Contiguous Subarray Match for Recipe in Menu
- Validate a Proposed Course Completion Sequence
More Snowflake interview questions
- Counterclockwise Perimeter of a Binary Tree Medium
- Thread-Safe Per-Key Token Bucket Rate Limiter Medium
- Log Fault Search and Service Outage Cascades Medium Pro
- Computing Inherited Access Grants Across a Permission DAG Medium Pro
- Minimum Edits to Form a Perfect Binary Tree Medium Pro
- Locate All Valid Sets in a Four-Feature Deck Hard Pro
- Multiway Tree Height Under Node Removal and Promotion Medium Pro
- Resulting N-ary Tree Height When Splicing Out Nodes Medium Pro
- Per-Key Sliding-Window Request Limiter Medium Pro
- Rooted Tree Height After Node Removals Medium Pro