Loading problem...
You are managing an academic curriculum containing n subjects, labeled from 1 to n. The curriculum includes a list of dependencies where each dependency is represented as a pair [prerequisite, subject], indicating that prerequisite must be completed before subject can be attempted.
During each study term, you may enroll in any number of subjects simultaneously, provided that all of their prerequisite subjects have been completed in previous terms. A subject cannot be taken in the same term as its prerequisite—it must be taken in a strictly later term.
Your goal is to determine the minimum number of study terms required to complete all n subjects in the curriculum. If it is impossible to complete all subjects due to circular dependencies (where subjects depend on each other in a cycle), return -1.
This problem models real-world academic planning scenarios where students must satisfy course prerequisites before advancing, and the goal is to graduate in the shortest possible time by optimizing concurrent enrollment.
n = 3
dependencies = [[1,3],[2,3]]2In the first study term, you can complete subjects 1 and 2 simultaneously since they have no prerequisites. In the second term, you can complete subject 3, which requires both subjects 1 and 2. Total: 2 terms.
n = 3
dependencies = [[1,2],[2,3],[3,1]]-1Subject 1 requires subject 3, subject 3 requires subject 2, and subject 2 requires subject 1—forming a circular dependency. No valid ordering exists, so it is impossible to complete all subjects.
n = 4
dependencies = [[1,2],[2,3],[3,4]]4The subjects form a linear chain: 1 → 2 → 3 → 4. Each subject depends on the previous one, so they must be completed one at a time across 4 separate study terms.
Constraints