Skip to main content
Back to problems
#582
Medium Algorithms

Kill process

Array Hash Table Tree Depth-First Search Breadth-First Search
70.4% acceptance
Mar 31, 2026
1131
21
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 ith process and ppid[i] is the ID of the ith 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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn kill_process(pid: Vec<i32>, ppid: Vec<i32>, kill: i32) -> Vec<i32> {
    use std::collections::HashMap;
    let mut children: HashMap<i32, Vec<i32>> = HashMap::new();
    for i in 0..pid.len() {
      children.entry(ppid[i]).or_default().push(pid[i]);
    }
    let mut result = Vec::new();
    let mut stack = vec![kill];
    while let Some(p) = stack.pop() {
      result.push(p);
      if let Some(ch) = children.get(&p) {
        for &c in ch {
          stack.push(c);
        }
      }
    }
    result
  }
}