Skip to the code
cf.
+25 XP

#446 Modules Safe From Import Loops

medium

A refactoring tool wants to know which modules are safe to move: a module is safe if no chain of imports starting from it ever reaches an import loop. Modules are numbered 0 to n - 1, and imports[i] = [a, b] means a imports b.

Write safeModules(n, imports) that returns the safe modules sorted ascending. A module that is itself part of a loop is not safe.

Example 1

Input: n = 5, imports = [[0,1],[1,2],[2,1],[3,4]]
Output: [3,4]

1 and 2 import each other, so they are in a loop, and 0 reaches that loop. 3 only reaches 4, which imports nothing.

Example 2

Input: n = 3, imports = []
Output: [0,1,2]

No imports at all, so nothing can reach a loop.

Constraints

  • 1 <= n <= 10000
  • 0 <= imports.length <= 50000
  • 0 <= a, b < n
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).