Ctrl K

Module Build Order

Medium
A project has n modules numbered from 0 to n - 1. The list deps describes how they depend on each other: a pair [a, b] means module a uses module b, so b has to be built before a. Modules are built one at a time. Decide whether there is an order in which all n modules can be built without breaking any dependency. Return True if such an order exists and False otherwise.
Example 1
n=4, deps=[[1, 0], [2, 1], [3, 1]] → True

The order 0, 1, 2, 3 works: module 1 waits only for 0, and modules 2 and 3 wait only for 1.

Example 2
n=3, deps=[[0, 1], [1, 2], [2, 0]] → False

Module 0 waits for 1, module 1 waits for 2, and module 2 waits for 0: a closed loop, nothing can go first.

Example 3
n=5, deps=[] → True

There are no dependencies, so the modules can be built in any order.

Constraints
  • 1 ≤ n ≤ 2000
  • 0 ≤ length of deps ≤ 5000
  • each element of deps is a pair [a, b] with 0 ≤ a, b < n
  • all pairs in deps are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsCourse Enrollment Queue MediumBest Roots for a Tree MediumRoutes That Always End MediumLongest Hike Through the Woods MediumDoes This Step Come First Medium
loading Python…
Input
n=4, deps=[[1, 0], [2, 1], [3, 1]]
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 82 tests on the server, hidden ones included.