All problems
0527MediumDepth-First SearchBreadth-First SearchGraph Theory

Pruning a Faulty Module and Its Imports

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3310Remove Methods From Project

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A codebase has count modules, numbered 0 through count - 1. The import graph is given as a list of directed pairs: imports[i] = [a, b] means module a imports module b. A module never imports itself and no pair is listed twice.

Module faulty has been found broken. A cleanup marks faulty together with every module that can be reached from it by following one or more imports, since those are only pulled in on its account.

The cleanup is only safe if nothing outside the marked group depends on it. So if any module that is not marked imports a module that is marked, the cleanup is called off and every module stays. Otherwise all the marked modules are deleted.

Return the numbers of the modules still in the codebase afterwards, in increasing order.

Examples

Example 1

Input
count = 5, faulty = 0, imports = [[0, 1], [1, 2], [3, 4]]
Output
[3, 4]

Following imports from module 0 reaches modules 1 and 2, so the marked group is 0, 1 and 2. The only other pair is [3, 4], whose importer and target are both unmarked, so the cleanup goes ahead and modules 3 and 4 remain.

Example 2

Input
count = 5, faulty = 1, imports = [[0, 1], [1, 2], [2, 3]]
Output
[0, 1, 2, 3, 4]

The marked group is 1, 2 and 3. Module 0 is not marked and it imports module 1, which is, so the cleanup is called off and all five modules stay.

Example 3

Input
count = 3, faulty = 2, imports = []
Output
[0, 1]

With no imports at all the marked group is just module 2, and nothing depends on it, so modules 0 and 1 remain.

Constraints

  • 1 <= count <= 10^5
  • 0 <= faulty <= count - 1
  • 0 <= imports.length <= 2 * 10^5
  • imports[i].length == 2
  • 0 <= imports[i][0], imports[i][1] <= count - 1
  • imports[i][0] != imports[i][1]
  • No two entries of imports are the same pair.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def surviving_modules(count: int, faulty: int, imports: list[list[int]]) -> list[int]:
Java
public List<Integer> survivingModules(int count, int faulty, int[][] imports)
September 7
Apply