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,needsmay 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
- Alarm Across the Campus (Easy)
- Does One Skill Lead to Another? (Easy)
- Flip the Fewest One-Way Signs (Easy)
- Letters of a Made-Up Language (Medium)
- Fewest Terms to Graduate (Medium)
- Budget Trip With Few Layovers (Medium)
- The Gentlest Hike (Medium)
- Wire Up the Sensors (Medium)
- Pick the Quietest Depot (Medium)
- Rebuild the Travel Route (Medium)
- Cross Before the Flood (Hard)
- How Many Fastest Routes? (Hard)
- Earliest Launch Day (Hard)
- Toll Roads With Coupons (Hard)