Skip to the code
+25 XP

#444 Longest Import Chain

medium

A bundle analyzer warns about deep import chains, because each level can delay startup. Modules are numbered 0 to n - 1, and imports[i] = [a, b] means module a imports module b. There are no circular imports.

Write longestChain(n, imports) that returns the number of modules in the longest chain m1 → m2 → ... → mk where each module imports the next. A single module on its own is a chain of 1.

Example 1

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

0 → 1 → 2 → 4 (or 0 → 3 → 2 → 4) has 4 modules.

Example 2

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

No imports, so every chain is a single module.

Constraints

  • 1 <= n <= 10000
  • 0 <= imports.length <= 50000
  • The imports never form a loop.
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).