Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

3310. Remove Methods From Project

Explanation:

To solve this problem, we can use a depth-first search (DFS) approach to identify and remove suspicious methods along with their dependencies. We will start by building a directed graph representing method invocations. Then, we will perform a DFS starting from the suspicious method k to mark all methods that are directly or indirectly invoked by k as suspicious. Finally, we will iterate through all methods and include only those that are not marked as suspicious in the final result.

Algorithm:

  1. Build a directed graph representing method invocations.
  2. Perform DFS starting from the suspicious method k to mark all suspicious methods.
  3. Iterate through all methods and include only those that are not marked as suspicious in the final result.

Time Complexity:

The time complexity of this approach is O(n + m), where n is the number of methods and m is the number of invocations.

Space Complexity:

The space complexity of this approach is O(n + m) for storing the graph and the visited array.

: :

class Solution {
    public int[] removeMethods(int n, int k, int[][] invocations) {
        List<Integer>[] graph = new ArrayList[n];
        for (int i = 0; i < n; i++) {
            graph[i] = new ArrayList<>();
        }
        for (int[] invocation : invocations) {
            graph[invocation[0]].add(invocation[1]);
        }
        
        boolean[] suspicious = new boolean[n];
        dfs(graph, k, suspicious);
        
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (!suspicious[i]) {
                result.add(i);
            }
        }
        
        return result.stream().mapToInt(Integer::intValue).toArray();
    }
    
    private void dfs(List<Integer>[] graph, int k, boolean[] suspicious) {
        suspicious[k] = true;
        for (int next : graph[k]) {
            if (!suspicious[next]) {
                dfs(graph, next, suspicious);
            }
        }
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.