Kill Process - Problem
Kill Process - Tree Traversal Challenge
You're managing a system where processes are organized in a tree structure. Each process can have multiple child processes, but only one parent process. When you kill a process, all of its descendants (children, grandchildren, etc.) must also be terminated.
Given two arrays:
โข
โข
Your task is to determine which processes will be killed when you terminate a specific process with ID
Example: If process 3 has children [5, 7] and process 5 has child [9], then killing process 3 will terminate processes [3, 5, 7, 9].
You're managing a system where processes are organized in a tree structure. Each process can have multiple child processes, but only one parent process. When you kill a process, all of its descendants (children, grandchildren, etc.) must also be terminated.
Given two arrays:
โข
pid[i] - the ID of the i-th processโข
ppid[i] - the parent ID of the i-th processYour task is to determine which processes will be killed when you terminate a specific process with ID
kill.Example: If process 3 has children [5, 7] and process 5 has child [9], then killing process 3 will terminate processes [3, 5, 7, 9].
Input & Output
example_1.py โ Basic Tree
$
Input:
pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5
โบ
Output:
[5, 10]
๐ก Note:
Process 5 has one child process 10. When we kill process 5, both processes 5 and 10 are terminated.
example_2.py โ Larger Tree
$
Input:
pid = [1,3,10,5], ppid = [3,0,5,3], kill = 3
โบ
Output:
[3, 1, 5, 10]
๐ก Note:
Process 3 is the root with children [1, 5]. Process 5 has child 10. Killing process 3 terminates the entire subtree: [3, 1, 5, 10].
example_3.py โ Single Process
$
Input:
pid = [1], ppid = [0], kill = 1
โบ
Output:
[1]
๐ก Note:
Only one process exists. Killing it returns [1].
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 ppid[i] = 0
- All the PIDs are distinct
- kill is guaranteed to be in pid
Visualization
Tap to expand
Understanding the Visualization
1
Build Organization Chart
Create a mapping from each manager to their direct reports
2
Start from Target
Begin termination process with the specified manager
3
Find All Reports
Use BFS/DFS to find everyone in the affected hierarchy
4
Terminate All
Add all affected employees to the termination list
Key Takeaway
๐ฏ Key Insight: Build a hash map for O(1) child lookup, then use tree traversal (BFS/DFS) to efficiently find all descendants in the process hierarchy.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code