AlgoInsight

DSA problem

Parallel Courses

MediumTopological SortPattern: Topological Sorttop600AmazonMicrosoftGoogleBloombergApple

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, nextCourse], representing a prerequisite relationship between course prevCourse and course nextCourse: course prevCourse has to be taken before course nextCourse.

In one semester, you can take any number of courses as long as you have taken all the prerequisites in the previous semesters 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.

This is the classic "shortest schedule" version of topological sort. Each semester corresponds to one BFS layer of Kahn's algorithm: every course whose prerequisites are already satisfied (in-degree zero) can be taken simultaneously. After processing that layer, we decrement the in-degree of each successor; any successor that hits zero becomes available for the next semester.

The algorithm bookkeeping is straightforward. Build the adjacency list and an in-degree array. Push every course with in-degree zero into a queue, then repeatedly pop the entire current queue as one semester, enqueueing every successor whose in-degree drops to zero. The answer is the number of layers processed — provided every course was visited. If any course is left unvisited at the end, the graph has a cycle and we return -1. The whole thing runs in O(n + e) time and O(n + e) space.

Examples

Example 1
Input: n = 3, relations = [[1,3],[2,3]]
Output: 2
Explanation: Take courses 1 and 2 in semester 1, then course 3 in semester 2.
Example 2
Input: n = 3, relations = [[1,2],[2,3],[3,1]]
Output: -1
Explanation: The dependencies form a cycle 1 -> 2 -> 3 -> 1, so no valid ordering exists.
Example 3
Input: n = 5, relations = [[1,2],[1,3],[3,4],[3,5]]
Output: 3
Explanation: Semester 1: course 1. Semester 2: courses 2 and 3. Semester 3: courses 4 and 5.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

graphtopological-sortbfskahn

Browse all DSA problems