Skip to content

582. Kill Process 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
 public:
  vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) {
    vector<int> ans;
    unordered_map<int, vector<int>> tree;

    for (int i = 0; i < pid.size(); ++i) {
      if (ppid[i] == 0)
        continue;
      tree[ppid[i]].push_back(pid[i]);
    }

    dfs(tree, kill, ans);
    return ans;
  }

 private:
  void dfs(const unordered_map<int, vector<int>>& tree, int u,
           vector<int>& ans) {
    ans.push_back(u);
    if (!tree.contains(u))
      return;
    for (const int v : tree.at(u))
      dfs(tree, v, ans);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
    List<Integer> ans = new ArrayList<>();
    Map<Integer, List<Integer>> tree = new HashMap<>();

    for (int i = 0; i < pid.size(); ++i) {
      if (ppid.get(i) == 0)
        continue;
      tree.putIfAbsent(ppid.get(i), new ArrayList<>());
      tree.get(ppid.get(i)).add(pid.get(i));
    }

    dfs(tree, kill, ans);
    return ans;
  }

  private void dfs(Map<Integer, List<Integer>> tree, int u, List<Integer> ans) {
    ans.add(u);
    for (final int v : tree.getOrDefault(u, new ArrayList<>()))
      dfs(tree, v, ans);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
  def killProcess(
      self,
      pid: list[int],
      ppid: list[int],
      kill: int,
  ) -> list[int]:
    ans = []
    tree = collections.defaultdict(list)

    for v, u in zip(pid, ppid):
      if u == 0:
        continue
      tree[u].append(v)

    def dfs(u: int) -> None:
      ans.append(u)
      for v in tree.get(u, []):
        dfs(v)

    dfs(kill)
    return ans