LeetCode Solutions

582. Kill Process

Time: $O(n)$

Space: $O(n)$

			

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.count(u))
      return;
    for (const int v : tree.at(u))
      dfs(tree, v, ans);
  }
};
			

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);
  }
}
			

class Solution:
  def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]:
    ans = []
    tree = 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