Skip to the code
+25 XP

#450 First Import That Closes a Loop

medium

A code review bot replays a project's history of new imports, one at a time. Modules are numbered 0 to n - 1, and imports[i] = [a, b] is the i-th import added: module a starts importing module b.

Write firstLoopImport(n, imports) that returns the index of the first import after which the modules contain a circular import (a module that can reach itself by following imports), or -1 if that never happens. An import of a module into itself closes a loop immediately.

Example 1

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

Before import 2 there are no loops. Adding 2 → 0 closes 0 → 1 → 2 → 0.

Example 2

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

Module 2 is reached twice, but nothing ever leads back.

Constraints

  • 1 <= n <= 10^5
  • 0 <= imports.length <= 10^5
  • 0 <= a, b < n
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

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