Fewest Removals to Cap a Rooted Tree's Height
Trees & GraphsAuto-graded · 25 test casesLast updated
Count the minimum non-root nodes to remove from a parent-array tree, splicing children upward, so the height is at most a limit; tests subtree heights and a path-decomposition argument.
You have a rooted tree with n nodes labelled 0 to n - 1, described by an array parents. Node 0 is the root and parents[0] == -1. For every other node i, parents[i] is the label of its parent. A parent's label may be larger than its child's label.
You may remove nodes from the tree. Removing a node does not remove its subtree. Instead, each of its children is reconnected to the nearest ancestor that has not been removed. If several removed nodes sit in a chain, the children climb past all of them.
Given an integer limit, return the smallest number of nodes you must remove so that the height of the remaining tree is at most limit.
Definitions and rules
- The height of a tree is the number of nodes on the longest path that starts at the root and goes downward. A tree made only of the root has height 1.
- The root can never be removed. Every other node may be removed.
- Only the minimum count is required. Different sets of removed nodes may reach the same minimum, and you do not need to report which ones.
Constraints
1 <= n == len(parents) <= 10^5parents[0] == -1. Fori >= 1,0 <= parents[i] <= n - 1, and the links form a single tree rooted at0with no cycles.1 <= limit <= n, so a valid answer always exists (removing every non-root node gives height 1).- The tree may be a single long path, so its depth can reach
n.
Examples
Example 1
Input: min_removals_for_height([-1, 0, 0, 1, 1, 3, 2], 3)
Output: 1
Example 2
Input: min_removals_for_height([-1, 0, 0, 1, 1, 3, 2], 2)
Output: 3
Example 3
Input: min_removals_for_height([-1, 0, 1, 2, 1, 1], 2)
Output: 2
Hints
Hint 1
Removing a node never makes any root-to-leaf path longer; it only drops that node from the paths through it. So you can reason about the original tree instead of simulating the splicing.
Hint 2
Compute, for every node v, the number of nodes on the longest downward path starting at v. Ask which non-root nodes can safely stay: a kept child of the root must have a downward path of at most limit - 1 nodes.
Hint 3
Try the answer 'count the non-root nodes whose subtree height is at least limit'. To prove it is a lower bound, split the tree into vertical chains by following each node to its tallest child, and count how many nodes each chain must lose. Use an iterative traversal, since the depth can reach 10^5.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Let h[v] be the number of nodes on the longest downward path that starts at v. A leaf has h = 1, and h[v] = 1 + max(h[child]) otherwise.
The answer is the number of non-root nodes v with h[v] >= limit.
Splicing children upward only removes nodes from root-to-leaf paths and never adds any. So the height after removals is the largest number of surviving nodes on any original root-to-leaf path. No simulation is needed.
Why it is correct
Let S = { v != 0 : h[v] >= limit }.
Removing S is enough. Take a root-to-leaf path in the resulting tree, 0 -> v1 -> .... The node v1 survives and is not the root, so h[v1] <= limit - 1. Everything that survives below v1 lies on an original downward path from v1, which has at most h[v1] <= limit - 1 nodes. Adding the root gives at most limit nodes.
Nothing smaller works. Split the tree into vertex-disjoint vertical chains: each node continues to its child with the largest h. A chain whose top is t runs to a leaf and has exactly h[t] nodes, and h drops by exactly 1 at each step down.
- Chain with top
t != 0. Extend it upward to the root to get a root-to-leaf path. At mostlimitnodes of that path can survive, and one of them is the root. So at mostlimit - 1chain nodes survive, and at leasth[t] - limit + 1must be removed. That equals the number of chain nodes withh >= limit, which are the top ones with heightsh[t], h[t]-1, ..., limit. - Chain starting at the root. It has
h[0]nodes and at mostlimitcan survive, so at leasth[0] - limitnon-root nodes must go. That equals the number of its non-root nodes withh >= limit.
The chains are disjoint, so the lower bounds add up to |S|. Any valid removal set therefore has at least |S| nodes, and S itself is valid.
Implementation notes
The depth can reach 10^5, so avoid recursion.
- Build child lists from
parents. - Produce a BFS order from the root. Parents always come before their children, regardless of label order.
- Walk that order in reverse, pushing
height[u] + 1intoheight[parents[u]]when it is larger. - Count non-root nodes with
height >= limit.
Edge cases:
n = 1gives 0.limit = 1givesn - 1.- If
limitis at least the original height, no non-root node qualifies, so the answer is 0.
Complexity
- Time: O(n).
- Space: O(n) for the child lists, the order array and the heights.
Reference solution
from typing import List
def min_removals_for_height(parents: List[int], limit: int) -> int:
n = len(parents)
# Child lists.
children = [[] for _ in range(n)]
for i in range(1, n):
children[parents[i]].append(i)
# BFS order: every parent appears before its children.
order = [0]
for u in order:
order.extend(children[u])
# height[v] = number of nodes on the longest downward path starting at v.
height = [1] * n
for u in reversed(order):
p = parents[u]
if p >= 0 and height[u] + 1 > height[p]:
height[p] = height[u] + 1
# Every non-root node whose subtree height is >= limit must be removed,
# and removing exactly those is enough.
return sum(1 for v in range(1, n) if height[v] >= limit)