Kill Process Problem
Description
LeetCode Problem 582.
You have n processes forming a rooted tree structure. You are given two integer arrays pid and ppid, where pid[i] is the ID of the i^th process and ppid[i] is the ID of the i^th process's parent process.
Each process has only one parent process but may have multiple children processes. Only one process has ppid[i] = 0, which means this process has no parent process (the root of the tree).
When a process is killed, all of its children processes will also be killed.
Given an integer kill representing the ID of a process you want to kill, return a list of the IDs of the processes that will be killed. You may return the answer in any order.
Example 1:

Input: pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5
Output: [5,10]
Explanation: The processes colored in red are the processes that should be killed.
Example 2:
Input: pid = [1], ppid = [0], kill = 1
Output: [1]
Constraints:
n == pid.lengthn == ppid.length1 <= n <= 5 * 10^41 <= pid[i] <= 5 * 10^40 <= ppid[i] <= 5 * 10^4- Only one process has no parent.
- All the values of
pidare unique. killis guaranteed to be inpid.
Solution
Approach: Build the Children Lists, Then Walk the Subtree
The input lists each process with its parent, but killing a process spreads down to its children. So first turn the two arrays into a map from each process ID to the list of its children: for every i, add pid[i] to children[ppid[i]].
The processes that die are exactly kill and everything below it in the tree. Start a depth-first walk at kill: pop a process, add it to the answer, and push all of its children. Every process in the subtree is reached once, because each one has a single parent.
The tree can be a single chain of up to 5 * 104 processes, so we use an explicit stack instead of recursion, which keeps the walk safe in languages with a small call stack. A process with no children simply has no entry in the map, so look it up with a default empty list.
Complexity: O(n) time and O(n) extra space for the children map and the stack.
from collections import defaultdict
class Solution:
def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]:
children = defaultdict(list)
for p, parent in zip(pid, ppid):
children[parent].append(p)
# Walk the subtree under kill with an explicit stack (the tree can be a long chain).
ans, stack = [], [kill]
while stack:
p = stack.pop()
ans.append(p)
stack.extend(children[p])
return ans