KatInterview

Fewest Removals to Cap a Rooted Tree's Height

Trees & GraphsAuto-graded · 25 test cases
MediumAuto-gradedTrees & Graphstreesubtree-heightiterative-bfs

Last 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^5
  • parents[0] == -1. For i >= 1, 0 <= parents[i] <= n - 1, and the links form a single tree rooted at 0 with 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.