FastPrepTree Height After Child Promotion

Tree Height After Child Promotion

Snowflake logoSnowflake● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

You are given a rooted n-ary tree and distinct non-root node IDs to delete. Deleting a node removes that node and attaches each of its current children directly to its parent. Apply every listed deletion and return the resulting tree height, measured as the number of nodes on the longest root-to-leaf path. The root remains, so a tree containing only the root has height 1.

For this exercise, nodes are labeled 1 through n, root 1, and parent[i - 2] is the parent of node i. Delete the node IDs in deleted. Deleting both an ancestor and a descendant is allowed; their children continue to be promoted, and the final surviving ancestry is independent of deletion order.

Function

heightAfterPromotions(parent: int[], deleted: int[]) → int

Examples

Example 1

parent = [1,1,1,2,2]deleted = [2]return = 2

Deleting an internal node promotes both children.

Example 2

parent = [1,2,3]deleted = []return = 4

An unchanged four-node chain has height four.

Example 3

parent = [1,2,2]deleted = [3]return = 3

Deleting one leaf preserves the other deep path.

Constraints

  • 1 <= n = parent.length + 1 <= 10000.
  • The parent array describes one valid tree rooted at 1; parent IDs need not be smaller than child IDs.
  • deleted contains distinct existing IDs from 2 through n, possibly none or all non-root nodes.

More Snowflake problems

See Snowflake hiring insights
public int heightAfterPromotions(int[] parent, int[] deleted) {
    // write your code here
}
parent[1,1,1,2,2]
deleted[2]
expected2
Checking account…