Short Python using dict and stack


  • 0
    class Solution(object):
        def killProcess(self, pid, ppid, kill):
            """
            :type pid: List[int]
            :type ppid: List[int]
            :type kill: int
            :rtype: List[int]
            """
            child = collections.defaultdict(list)
            for i in range(len(pid)):
                if ppid[i]: child[ppid[i]].append(pid[i])
            
            res, stack = [], [kill]
            while stack:
                curr = stack.pop()
                res.append(curr)
                stack.extend(child[curr])
            return res
    

  • 0
    D

    @realisking I had the same idea. You can actually get away with just having the stack by itself.

    def killProcess(self, pid, ppid, kill):
        """
        :type pid: List[int]
        :type ppid: List[int]
        :type kill: int
        :rtype: List[int]
        """
        N = len(pid)
        d = defaultdict(list)
        for i in xrange(N):
            d[ppid[i]].append(pid[i])
        
        ans = [kill]
        i = 0
        while i < len(ans):
            if ans[i] in d: ans += d[ans[i]]
            i += 1
        return ans

  • 0
    L

    Could get rid of an extra 2 lines

    from collections import defaultdict
    class Solution(object):
        def killProcess(self, pid, ppid, kill):
            """
            :type pid: List[int]
            :type ppid: List[int]
            :type kill: int
            :rtype: List[int]
            """
            N = len(pid)
            d = defaultdict(list)
            for i in xrange(N):
                d[ppid[i]].append(pid[i])
            ret=[kill]
            for i in ret:
                if i in d: ret.extend(d[i])
            return ret

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.