Remove Methods From Project Problem
Description
LeetCode Problem 3310.
You are maintaining a project that has n methods numbered from 0 to n - 1.
You are given two integers n and k, and a 2D integer array invocations, where invocations[i] = [a_i, b_i] indicates that method a_i invokes method b_i.
There is a known bug in method k. Method k, along with any method invoked by it, either directly or indirectly, are considered suspicious and we aim to remove them.
A group of methods can only be removed if no method outside the group invokes any methods within it.
Return an array containing all the remaining methods after removing all the suspicious methods. You may return the answer in any order. If it is not possible to remove all the suspicious methods, none should be removed.
Example 1:
Input: n = 4, k = 1, invocations = [[1,2],[0,1],[3,2]]
Output: [0,1,2,3]
Explanation:

Method 2 and method 1 are suspicious, but they are directly invoked by methods 3 and 0, which are not suspicious. We return all elements without removing anything.
Example 2:
Input: n = 5, k = 0, invocations = [[1,2],[0,2],[0,1],[3,4]]
Output: [3,4]
Explanation:

Methods 0, 1, and 2 are suspicious and they are not directly invoked by any other method. We can remove them.
Example 3:
Input: n = 3, k = 2, invocations = [[1,2],[0,1],[2,0]]
Output: []
Explanation:

All methods are suspicious. We can remove them.
Constraints:
1 <= n <= 10^50 <= k <= n - 10 <= invocations.length <= 2 * 10^5invocations[i] == [a_i, b_i]0 <= a_i, b_i <= n - 1a_i != b_iinvocations[i] != invocations[j]
Solution
Approach: DFS from k, then check the edges
Follow the invocations from k with a DFS (an explicit stack, since the call chain can be 10^5 long) and mark every method reached as suspicious.
The suspicious group can be removed only if no outside method calls into it. A suspicious method never calls a non-suspicious one, because everything it calls is reached too. So it is enough to look at each invocation a -> b: if a is not suspicious and b is, removal is impossible and all methods are returned. Otherwise return the methods that are not suspicious.
Complexity: O(n + m) time and O(n + m) space, where n is the number of methods and m the number of invocations.
class Solution:
def remainingMethods(
self, n: int, k: int, invocations: List[List[int]]
) -> List[int]:
g = [[] for _ in range(n)]
for a, b in invocations:
g[a].append(b)
suspicious = [False] * n
suspicious[k] = True
stack = [k]
while stack:
i = stack.pop()
for j in g[i]:
if not suspicious[j]:
suspicious[j] = True
stack.append(j)
for a, b in invocations:
if not suspicious[a] and suspicious[b]:
return list(range(n))
return [i for i in range(n) if not suspicious[i]]