#3310

Remove Methods From Project

Medium
Depth-First SearchBreadth-First SearchGraph TheoryGraph Traversal (DFS/BFS)Dependency Resolution
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m)
Space
O(1)
O(n)
💡

Intuition

Time O(n + m)Space O(n)

In the optimal approach, we use Depth-First Search (DFS) to mark all methods that are suspicious, then check if any of these methods can be reached from other methods. This is efficient and avoids unnecessary checks.

⚙️

Algorithm

4 steps
  1. 1Step 1: Build a graph from the invocations list.
  2. 2Step 2: Use DFS to mark all methods that can be reached from method k as suspicious.
  3. 3Step 3: Create a set to track non-removable methods based on the invocations.
  4. 4Step 4: Return all methods that are not suspicious or are marked as non-removable.
solution.py27 lines
1# Full working Python code
2from collections import defaultdict
3
4def remove_methods(n, k, invocations):
5    graph = defaultdict(list)
6    for a, b in invocations:
7        graph[a].append(b)
8
9    suspicious = set()
10    visited = set()
11
12    def dfs(method):
13        if method in visited:
14            return
15        visited.add(method)
16        suspicious.add(method)
17        for neighbor in graph[method]:
18            dfs(neighbor)
19
20    dfs(k)
21
22    non_removable = set()
23    for a, b in invocations:
24        if b in suspicious:
25            non_removable.add(a)
26
27    return [i for i in range(n) if i not in suspicious or i in non_removable]

Complexity note: The complexity is O(n + m) where n is the number of methods and m is the number of invocations. This is because we traverse each method and invocation once.

  • 1Understanding the relationship between methods is crucial; methods can invoke others, creating a dependency graph.
  • 2Using DFS effectively helps in marking all reachable methods from a suspicious method.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.