Save 25%Black Friday: 25% off all plans — use code BLACKFRIDAY2026 at checkout. Ends Friday, Dec 4.Claim the deal

A forest is represented by an integer array parentIndex, where every node is identified by its index. For a node i, parentIndex[i] is the index of its direct parent, and a root is its own parent.

The input initially represents a valid forest with no deleted nodes. A parent may have a larger index than its child.

Given parentIndex and a node index target, delete target and all of its descendants by setting their entries to -1. Modify parentIndex in place without changing its length or the indices of any remaining nodes, and return the same modified array.

Constraints:

  • 1 ≤ parentIndex.length ≤ 105
  • 0 ≤ target < parentIndex.length

Example 1:

Input: parentIndex = [0, 0, 0, 3, 3, 2, 4], target = 2 Output: [0, 0, -1, 3, 3, -1, 4] Explanation: Node 5 is a descendant of node 2, so both entries become -1. The tree rooted at node 3 remains unchanged.

Example 2:

Input: parentIndex = [0, 0, 0, 3, 3, 2, 4], target = 0 Output: [-1, -1, -1, 3, 3, -1, 4]

Example 3:

Input: parentIndex = [0, 1, 1, 1, 3, 3], target = 3 Output: [0, 1, 1, -1, -1, -1]


Accepted
779/1.7k
Acceptance Rate45.8%
Test Cases
Input
parentIndex =
target =
Output
Expected