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.
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.
Input: n = 3, imports = [[0,1],[0,2],[1,2]] Output: -1
Module 2 is reached twice, but nothing ever leads back.
1 <= n <= 5000 <= imports.length <= 20000 <= a, b < nRun 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).
I'm here to help with #450 First Import That Closes a Loop. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.