Skip to main content
LeetCode 1136, Medium. Topics: Graph, Topological Sort. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 26 parametrized pytest cases, and a playground notebook:

Problem

You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCourse_i, nextCourse_i], representing a prerequisite relationship between course prevCourse_i and course nextCourse_i: course prevCourse_i has to be taken before course nextCourse_i. In one semester, you can take any number of courses as long as you have taken all the prerequisites in the previous semester for the courses you are taking. Return the minimum number of semesters needed to take all courses. If there is no way to take all the courses, return -1.

Examples

Example 1
Explanation: In the first semester, you can take courses 1 and 2. In the second semester, you can take course 3. Example 2
Explanation: No course can be studied because they are prerequisites of each other.

Constraints

  • 1 <= n <= 5000
  • 1 <= relations.length <= 5000
  • relations[i].length == 2
  • 1 <= prevCourse_i, nextCourse_i <= n
  • prevCourse_i != nextCourse_i
  • All the pairs [prevCourse_i, nextCourse_i] are unique.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026