#3310
Medium Algorithms Remove methods from project
Depth-First Search Breadth-First Search Graph Theory
50.4% acceptance
Feb 23, 2026
156
57
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] = [ai, bi] indicates that method ai invokes method bi.
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.
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn remaining_methods(n: i32, k: i32, invocations: Vec<Vec<i32>>) -> Vec<i32> {
let n = n as usize;
let k = k as usize;
let mut adj = vec![vec![]; n];
for inv in &invocations {
adj[inv[0] as usize].push(inv[1] as usize);
}
// BFS/DFS from k to find all suspicious methods
let mut suspicious = vec![false; n];
let mut stack = vec![k];
suspicious[k] = true;
while let Some(node) = stack.pop() {
for &next in &adj[node] {
if !suspicious[next] {
suspicious[next] = true;
stack.push(next);
}
}
}
// Check if any non-suspicious method invokes a suspicious method
for inv in &invocations {
let a = inv[0] as usize;
let b = inv[1] as usize;
if !suspicious[a] && suspicious[b] {
// Cannot remove - return all
return (0..n as i32).collect();
}
}
// Return non-suspicious methods
(0..n).filter(|&i| !suspicious[i]).map(|i| i as i32).collect()
}
}