Delete and Compact a Forest Subtree
Updated
Problem statement
A forest of nodes numbered from 0 through n - 1 is represented by parent. Every root points to itself, and every nonroot entry is the index of its parent.
Delete the node deleteIndex and its entire subtree. Keep surviving nodes in their original relative order, assign them consecutive new indices beginning at 0, and return their remapped parent array. A surviving root points to its own new index.
If every node is deleted, return an empty array.
Function
deleteAndCompactSubtree(parent: int[], deleteIndex: int) → int[]Examples
Example 1
parent = [0,0,0,2,4,4]deleteIndex = 2return = [0,0,2,2]Survivors 0, 1, 4, and 5 become indices 0 through 3.
Example 2
parent = [0,0,1,1]deleteIndex = 3return = [0,0,1]Removing the last leaf leaves all earlier indices unchanged.
Example 3
parent = [0,0,2,2,4]deleteIndex = 0return = [0,0,2]Surviving roots and their children are remapped after the removed prefix.
Constraints
1 <= parent.length <= 200000.0 <= parent[i] < parent.length.- The parent links form a valid forest whose only cycles are self-pointing roots.
0 <= deleteIndex < parent.length.
More Pinterest Phone Screen questions
- Shortest Pin Path Through TopicsPHONE SCREEN · Seen Nov 2026
- Top K Pins with Insert and QueryPHONE SCREEN · Seen Nov 2026
- Pins Violation Log QueriesPHONE SCREEN · Seen Nov 2026
- Sparse Matrix Addition and MultiplicationPHONE SCREEN · Seen Nov 2026
- Minimum Bus Routes to a DestinationPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Optimal Account BalancingPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Aggregate Matching IPv4 Addresses Across ResponsesPHONE SCREEN · Seen Oct 2026
- Escape Room LeaderboardPHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2026
- Shortest Way to Form a Target StringPHONE SCREEN · Seen Sep 2026
- Time-Ordered Elevator DispatchPHONE SCREEN · Seen Sep 2026
Similar questions at other companies
- Validate a Tree From Its Parent ArrayGoogle · PHONE SCREENGoogle interview questions
- Filter Undesired Comments and Their DescendantsReddit · PHONE SCREEN · ONSITE INTERVIEWReddit interview questions
- Island Count and Maximum AreaOracle · ONSITE INTERVIEWOracle interview questions
- Aggregate Machine TopologyOpenAI · PHONE SCREEN · ONSITE INTERVIEWOpenAI interview questions
- Deterministic Depth-First Graph TraversalWaymo · PHONE SCREENWaymo interview questions
- Diameter of an Acyclic Undirected GraphSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Count Islands in a Binary GridApple · PHONE SCREENApple interview questions
- Render a Comment HierarchyAmazon · ONSITE INTERVIEW
- Query Whether an Island Size ExistsMeta · ONSITE INTERVIEWMeta interview questions
- Pacific Atlantic Water FlowAnduril · PHONE SCREENAnduril interview questions