582. Kill Process
Last updated
Last updated
/**
* Time complexity : O(n). We need to traverse over the ppid array of size
* n once. Also, atmost n additions/removals are done from the queue.
* Space complexity : O(n). mapmap of size n is used.
*/
class Solution {
public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
List<Integer> resultList = new ArrayList();
Map<Integer, List<Integer>> map = new HashMap();
for(int i = 0; i < ppid.size(); i++) {
int ppidVal = ppid.get(i);
if(ppidVal > 0) {
List<Integer> group = map.getOrDefault(ppidVal, new ArrayList<Integer>());
group.add(pid.get(i));
map.put(ppidVal, group);
}
}
Queue<Integer> queue = new LinkedList();
queue.add(kill);
while(!queue.isEmpty()) {
int node = queue.poll();
resultList.add(node);
if(map.containsKey(node)) {
for(int child: map.get(node)) {
queue.add(child);
}
}
}
return resultList;
}
}