call(back)
Algorithms & Data StructureseasySign in to star problems

Delete a Node From a Forest Stored as a Parent Array

A forest is stored as parent[i], the parent index of node i, with -1 for a root. Delete node x: its children are re-parented to x's parent (they become roots if x was a root), and x's own entry becomes null. Return the new array without renumbering the other nodes.

deleteNode([-1, 0, 0, 1, 1], 1)  ->  [-1, null, 0, 0, 0]
deleteNode([-1, 0, 0, 1, 1], 0)  ->  [null, -1, -1, 1, 1]

Hints

Hint 1

One pass: every entry equal to x is replaced by parent[x]; then null out x.

Asked at