Finish Every Training Module

Easy · Topological Sort & Shortest Paths · about 15 min

A new hire must complete n training modules, numbered 0 to n - 1. Each pair [a, b] in needs means module b must be completed before module a. A pair [a, a] means a module needs itself, which can never be done.

Return True (Python) / true (JavaScript) if every module can be completed, otherwise False / false.

  • 1 <= n <= 2000, needs may be empty and may repeat a pair.
  • The modules may form several separate groups.

Example: can_finish_modules(4, [[1, 0], [2, 1], [3, 2]]) → True (do 0, 1, 2, 3).

Example: can_finish_modules(2, [[0, 1], [1, 0]]) → False (each waits for the other).

Hints

  • Think of the rules as arrows. When is it impossible to finish? Only when the arrows go round in a loop.
  • Count how many unfinished modules each module is still waiting for. A module with zero can be done now.
  • Each time you finish a module, lower the waiting count of the modules that needed it. At the end, compare how many you finished with n.

Learn the pattern first: the Topological Sort & Shortest Paths lesson.

More Topological Sort & Shortest Paths problems