Kill Process

medium bfs graph

Problem

pid[i]'s parent is ppid[i]. Given the pid to kill, return every pid that is killed (the pid and all descendants).

Inputpid=[1,3,10,5] ppid=[3,0,5,3] kill=5
Output[5,10]
5's children = [10]; 10 has no children.

def kill_process(pid, ppid, kill):
    from collections import defaultdict, deque
    g = defaultdict(list)
    for p, pp in zip(pid, ppid): g[pp].append(p)
    out, q = [], deque([kill])
    while q:
        x = q.popleft(); out.append(x); q.extend(g[x])
    return out
function killProcess(pid, ppid, kill) {
  const g = new Map();
  for (let i = 0; i < pid.length; i++) (g.get(ppid[i]) ?? g.set(ppid[i], []).get(ppid[i])).push(pid[i]);
  const out = [], q = [kill];
  while (q.length) { const x = q.shift(); out.push(x); (g.get(x) || []).forEach(c => q.push(c)); }
  return out;
}
List killProcess(List pid, List ppid, int kill) {
    Map> g = new HashMap<>();
    for (int i = 0; i < pid.size(); i++) g.computeIfAbsent(ppid.get(i), k -> new ArrayList<>()).add(pid.get(i));
    List out = new ArrayList<>();
    Deque q = new ArrayDeque<>(); q.add(kill);
    while (!q.isEmpty()) {
        int x = q.poll(); out.add(x);
        if (g.containsKey(x)) q.addAll(g.get(x));
    }
    return out;
}
vector killProcess(vector& pid, vector& ppid, int kill) {
    unordered_map> g;
    for (int i = 0; i < (int)pid.size(); i++) g[ppid[i]].push_back(pid[i]);
    vector out; queue q; q.push(kill);
    while (!q.empty()) {
        int x = q.front(); q.pop(); out.push_back(x);
        for (int c : g[x]) q.push(c);
    }
    return out;
}
Time: O(n) Space: O(n)