Tuesday, February 16, 2021

[LeetCode] Kill Process

Problem: Given n processes, each process has a unique PID (process id) and its PPID (parent process id).

Each process only has one parent process, but may have one or more children processes. This is just like a tree structure. Only one process has PPID that is 0, which means this process has no parent process. All the PIDs will be distinct positive integers.

We use two list of integers to represent a list of processes, where the first list contains PID for each process and the second list contains the corresponding PPID.

Now given the two lists, and a PID representing a process you want to kill, return a list of PIDs of processes that will be killed in the end. You should assume that when a process is killed, all its children processes will be killed. No order is required for the final answer.

Example:

Input: 
pid =  [1, 3, 10, 5]
ppid = [3, 0, 5, 3]
kill = 5
Output: [5,10]
Explanation: 
           3
         /   \
        1     5
             /
            10
Kill 5 will also kill 10.


Approach: If you look at the example, you will catch that it's kind of tree structure. First using pid and ppid we will build a tree (using hash map) and then we will apply pre-order traversal / DFS from the pid which is given as input to be killed. Basically we will return the whole subtree of which root is the given pid.


Implementation in C#:

    public IList<int> KillProcess(IList<int> pid, IList<int> ppid, int kill) 

    {

        if (pid.Count == 0)

        {

            return new List<int>();

        }    

        Dictionary<int, List<int>> processTree = this.BuildProcessTree(pid, ppid);

        if (!processTree.ContainsKey(kill))

        {

            return new List<int> { kill };

        }

        List<int> result = new List<int>();

        this.GetKilledProcessIds(kill, processTree, ref result);

        return result;

    }


    private Dictionary<int, List<int>> BuildProcessTree(IList<int> pid, IList<int> ppid)

    {

        Dictionary<int, List<int>> processTree = new Dictionary<int, List<int>>();

        for (int i = 0; i < pid.Count; ++i)

        {

            if (!processTree.ContainsKey(ppid[i]))

            {

                processTree.Add(ppid[i], new List<int>());

            }

            processTree[ppid[i]].Add(pid[i]);

        }

        return processTree;

    }

    

    private void GetKilledProcessIds(int kill, Dictionary<int, List<int>> processTree, ref List<int> result)

    {

        result.Add(kill);

        if (!processTree.ContainsKey(kill))

        {

            return;

        }

        foreach(int pid in processTree[kill])

        {

            this.GetKilledProcessIds(pid, processTree, ref result);

        }

    }


Complexity: O(n)

No comments:

Post a Comment