Kill Process — LeetCode 582 Python Solution
MediumLeetCode PremiumTreeDepth-First SearchBreadth-First SearchArrayHash Table
- Problem
- #582
- Pattern
- Tree Traversal
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You have n processes forming a rooted tree structure. You are given two integer arrays pid and ppid, where pid[i] is the ID of the ith process and ppid[i] is the ID of the ith process's parent process.
Example
- Input
- pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5
- Output
- [5,10]
- Explanation
- The processes colored in red are the processes that should be killed.
Python solution
Python
class Solution:
def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]:
def dfs(i: int):
ans.append(i)
for j in g[i]:
dfs(j)
g = defaultdict(list)
for i, p in zip(pid, ppid):
g[p].append(i)
ans = []
dfs(kill)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 582. Kill Process is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 582. Kill Process?
- LeetCode 582. Kill Process is rated Medium on LeetCode.
- What is the time complexity of LeetCode 582. Kill Process?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 582. Kill Process?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 582. Kill Process cover?
- LeetCode 582. Kill Process is tagged Tree, Depth-First Search, Breadth-First Search, Array and Hash Table on LeetCode.
- Is LeetCode 582. Kill Process a premium problem?
- Yes. LeetCode 582. Kill Process is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.