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.

Input & Output

Example 1 — Basic Tree Structure
$ Input: pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5
Output: [5,10]
💡 Note: Process 5 has child 10. When we kill 5, both 5 and 10 are terminated.
Example 2 — Deeper Tree
$ Input: pid = [1,2,3,4,5], ppid = [0,1,1,3,3], kill = 3
Output: [3,4,5]
💡 Note: Process 3 has children 4 and 5. Killing 3 removes processes 3, 4, and 5.
Example 3 — Root Process
$ Input: pid = [1,2,3], ppid = [0,1,1], kill = 1
Output: [1,2,3]
💡 Note: Process 1 is root with children 2 and 3. Killing root kills entire tree.

Constraints

  • n == pid.length
  • n == ppid.length
  • 1 ≤ n ≤ 5 × 104
  • 1 ≤ pid[i] ≤ 5 × 104
  • 0 ≤ ppid[i] ≤ 5 × 104
  • Only one process has no parent
  • All the PIDs are distinct
  • kill is guaranteed to be in pid

Visualization

Tap to expand
Kill Process: Tree TerminationOriginal Tree12345KILLProcess 3TargetAfter Killing Process 312345Killed Processes: [3, 4, 5]
Understanding the Visualization
1
Input
Process tree with parent-child relationships
2
Kill Target
Identify process to terminate
3
Output
All processes that get killed (target + descendants)
Key Takeaway
🎯 Key Insight: Build parent-child relationships first, then traverse the subtree from the target process
Asked in
Facebook 12 Google 8 Amazon 6 Microsoft 4
32.0K Views
Medium Frequency
~25 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen