KatInterview

Prune a Branch from a Parent-Array Forest

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphsforestdfsparent-array

Last updated

Remove a node and its entire subtree from a forest stored as a parent array, either by marking slots with -1 or by compacting indices and remapping parent pointers.

Prune a Branch from a Parent-Array Forest

A forest is stored in a zero-indexed list parents of length n. Entry parents[i] is the index of the parent of node i. A node that is the root of its tree stores its own index: parents[i] == i. The input is always a valid forest, so following parent links from any node always ends at a self-referencing root.

You are given a node index target and a boolean compact. Pruning removes target together with every one of its descendants, that is, every node whose chain of parents passes through target (including target itself).

Return a new list describing the forest after pruning, according to the mode:

Mark mode (compact = False)

  • The result has the same length n as the input.
  • For target and each of its descendants, the entry is set to -1.
  • Every other entry is left exactly as in the input, so surviving nodes keep their indices and parent values.

Compact mode (compact = True)

  • Removed nodes are dropped from the list entirely.
  • The surviving nodes keep their relative order and are renumbered consecutively from 0 to k - 1, where k is the number of survivors.
  • Each surviving node's parent value is rewritten using the new numbering.
  • A surviving root still points to itself under the new numbering (result[j] == j).
  • If no node survives, return an empty list.

A surviving node never has a removed parent, because a child of a removed node is itself removed.

Constraints

  • 1 <= len(parents) <= 10^5
  • 0 <= parents[i] < len(parents)
  • 0 <= target < len(parents)
  • The input is a valid forest: no cycles other than root self-loops.
  • Very deep trees are possible, so avoid relying on deep recursion.

Examples

Example 1

Input: prune_branch([0, 0, 1, 1, 2], 1, False)

Output: [0, -1, -1, -1, -1]

Example 2

Input: prune_branch([0, 0, 2, 2, 3], 0, True)

Output: [0, 0, 1]

Hints

Hint 1

A parent array only lets you walk upward. Think about building a children list once so you can walk downward from the target. Remember not to list a root as its own child.

Hint 2

Collect the removed set with an iterative traversal (explicit stack) starting at target, marking each visited node so it is handled once.

Hint 3

For compact mode, scan nodes in increasing order and assign each survivor the next free new index. Then map each survivor's parent through that table; a surviving root maps to itself automatically.