KatInterview

582. Kill Process

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find all processes that are killed when a specific process is killed. We are given a list of process IDs (pid) and their corresponding parent process IDs (ppid). This relationship forms a tree structure. The core rule is that killing a process also kills all of its children, its children's children, and so on. This means we need to identify the entire subtree rooted at the given kill process ID and return all the process IDs in that subtree.

Solution

Kill Process in Python

from collections import defaultdict, deque

class Solution:
    def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]:
        # Use a defaultdict to represent the tree (adjacency list).
        # Keys are parent PIDs, values are lists of their child PIDs.
        adj = defaultdict(list)
        for child, parent in zip(pid, ppid):
            adj[parent].append(child)

        # This will store the final list of all killed processes.
        killed_processes = []
        
        # Use a deque for an efficient queue in BFS.
        q = deque()
        
        # Start the traversal from the process to be killed.
        q.append(kill)
        killed_processes.append(kill)

        # Perform BFS to find all descendants.
        while q:
            current_process = q.popleft()
            
            # For each child of the current process...
            # The defaultdict will return an empty list for leaf nodes,
            # so no explicit 'if key in adj' check is needed.
            for child in adj[current_process]:
                # Add the child to the results and to the queue for further traversal.
                killed_processes.append(child)
                q.append(child)

        return killed_processes

Kill Process in Java

class Solution {
    public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
        // Use a map to represent the tree structure (adjacency list).
        // Key: parent process ID, Value: list of its children process IDs.
        Map<Integer, List<Integer>> adj = new HashMap<>();
        for (int i = 0; i < ppid.size(); i++) {
            int parent = ppid.get(i);
            int child = pid.get(i);
            // A concise way to get the list for the parent, or create it if it doesn't exist.
            adj.computeIfAbsent(parent, k -> new ArrayList<>()).add(child);
        }

        // List to store the IDs of all processes to be killed.
        List<Integer> killedProcesses = new ArrayList<>();
        
        // Use a queue for Breadth-First Search (BFS).
        Queue<Integer> queue = new LinkedList<>();
        
        // Start the process by adding the initial `kill` process.
        queue.add(kill);
        killedProcesses.add(kill);

        // Perform BFS to find all descendants.
        while (!queue.isEmpty()) {
            int currentProcess = queue.poll();

            // Check if the current process has any children.
            if (adj.containsKey(currentProcess)) {
                // Add all children to the queue and the result list.
                for (int child : adj.get(currentProcess)) {
                    killedProcesses.add(child);
                    queue.add(child);
                }
            }
        }

        return killedProcesses;
    }
}

Kill Process in C++

class Solution {
public:
    vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) {
        // Use a hash map to represent the tree, mapping a parent process ID
        // to a list of its direct children process IDs.
        unordered_map<int, vector<int>> adj;
        for (int i = 0; i < pid.size(); ++i) {
            adj[ppid[i]].push_back(pid[i]);
        }

        // This will store the final list of all killed processes.
        vector<int> killed_processes;
        
        // Use a queue for Breadth-First Search (BFS).
        queue<int> q;
        
        // Start the BFS from the process we want to kill.
        q.push(kill);
        killed_processes.push_back(kill);

        // Perform BFS to find all descendants.
        while (!q.empty()) {
            int current_process = q.front();
            q.pop();

            // Find all children of the current process.
            // The `if` check handles leaf nodes (processes with no children).
            if (adj.count(current_process)) {
                // For each child, add it to the result list and to the queue
                // so its own children will be processed later.
                for (int child : adj[current_process]) {
                    killed_processes.push_back(child);
                    q.push(child);
                }
            }
        }

        return killed_processes;
    }
};

Kill Process in TypeScript

function killProcess(pid: number[], ppid: number[], kill: number): number[] {
    // Use a Map to represent the tree structure (adjacency list).
    // Key: parent process ID, Value: array of its children process IDs.
    const adj = new Map<number, number[]>();
    for (let i = 0; i < ppid.length; i++) {
        const parent = ppid[i];
        const child = pid[i];
        if (!adj.has(parent)) {
            adj.set(parent, []);
        }
        adj.get(parent)!.push(child);
    }

    // Array to store the IDs of all processes to be killed.
    const killedProcesses: number[] = [];
    
    // Use a simple array as a queue for Breadth-First Search (BFS).
    const queue: number[] = [];

    // Start the process by adding the initial `kill` process.
    queue.push(kill);
    killedProcesses.push(kill);

    // Perform BFS to find all descendants.
    while (queue.length > 0) {
        // `shift()` dequeues the first element.
        const currentProcess = queue.shift()!;

        // Check if the current process has any children.
        if (adj.has(currentProcess)) {
            const children = adj.get(currentProcess)!;
            // Add all children to the queue and the result list.
            for (const child of children) {
                killedProcesses.push(child);
                queue.push(child);
            }
        }
    }

    return killedProcesses;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.