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:
โ€ข pid[i] - the ID of the i-th process
โ€ข ppid[i] - the parent ID of the i-th process

Your 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
Process Tree Termination VisualizationCEOPID: 3TARGET TO KILLManager APID: 5Manager BPID: 7EmployeePID: 9EmployeePID: 1๐Ÿ”ฅ TERMINATION CASCADEWhen CEO (PID: 3) is terminated:โ†’ All direct reports (Manager A: 5, Manager B: 7, Employee: 1) are also terminatedโ†’ Manager A's reports (Employee: 9) are also terminatedResult: [3, 5, 7, 1, 9]
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.
Asked in
Facebook 35 Google 28 Amazon 22 Microsoft 15
73.9K Views
Medium Frequency
~15 min Avg. Time
1.8K 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