Fewest Terms to Graduate
Medium · Topological Sort & Shortest Paths · about 20 min
A degree has n courses, numbered 0 to n - 1. Each [before, after] in needs means course before must be passed in an earlier term than course after. You may take any number of courses in one term.
Return the fewest terms needed to pass every course, or -1 if that is impossible.
1 <= n <= 5000, pairs may repeat.
Example: fewest_terms(3, [[0, 2], [1, 2]]) → 2 (courses 0 and 1 in term 1, course 2 in term 2).
Hints
- Which courses can you take in the very first term? Those with no prerequisites.
- After a term, some courses lose their last unpassed prerequisite. They form the next term.
- Count the terms, and check at the end that every course was taken.
Learn the pattern first: the Topological Sort & Shortest Paths lesson.
More Topological Sort & Shortest Paths problems
- Finish Every Training Module (Easy)
- 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)
- 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)