progress

~/problems / Graphs / DFS and connected components

Cutting a branch out of a forest

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min Pinterest

A forest of nodes 0 .. n-1 is stored as a parent array: parent[i] is the parent of i, and a root is its own parent. There may be several roots, and a parent's number can be larger or smaller than its child's.

Write

def delete_subtree(parent: list[int], node: int) -> list[int]

that deletes node and everything below it, returning the new array: deleted entries become -1, all others stay as they were. Don't modify the input.

#   tree A:   3            tree B:  5
#            / \                    |
#           0   4                   2
#               |
#               1
parent = [3, 4, 5, 3, 3, 5]
delete_subtree(parent, 4)   # [3, -1, 5, 3, -1, 5]
delete_subtree(parent, 3)   # [-1, -1, 5, -1, -1, 5]
delete_subtree(parent, 2)   # [3, 4, -1, 3, 3, 5]

Up to 200,000 nodes.

⭐ Bonus: a speed test with a 200,000-node chain earns a star in O(n). Walking up from every node is quadratic there, and recursing down the chain overflows Python's stack.

Show hint

Build a children list from parent (skipping each root's self-link), then walk down from node with an explicit stack.

Topic: DFS and connected components. Iterative DFS / flood fill; count and label components.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc