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 - Hash Map + DFS INPUT Process Tree Structure 3 root 1 5 KILL 10 pid = [1, 3, 10, 5] ppid = [3, 0, 5, 3] kill = 5 Target + Children ALGORITHM STEPS 1 Build Children Map Map parent --> children 3 --> [1, 5] 5 --> [10] 0 --> [3] (root) 2 Start DFS from kill=5 Add 5 to result list 3 Traverse Children 5's children: [10] DFS(5) --> add 5 DFS(10) --> add 10 no children, return 4 Return Result All killed processes FINAL RESULT Killed Processes 5 10 Output: [5, 10] OK - 2 processes Key Insight: Build a HashMap (parent --> children list) from ppid/pid arrays. Then perform DFS starting from the kill target, recursively adding each process and all its descendants to the result. Time: O(n), Space: O(n) TutorialsPoint - Kill Process | Hash Map + DFS Approach
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