Parallel Courses
Problem Statement
There are n courses, labelled 1 to n. Each pair relations[i] = [prevCourse, nextCourse] means prevCourse must be taken in an earlier semester than nextCourse.
In one semester you can take any number of courses, as long as every prerequisite of each course was taken in an earlier semester. Return the minimum number of semesters needed to take every course. If it is impossible, return -1.
n, the number of courses, and relations, a list of pairs [prevCourse, nextCourse].
The minimum number of semesters, or -1 when the relations contain a loop.
Semester 1 takes courses 1 and 6, which need nothing. Semester 2 takes 2 and 3. Semester 3 takes 4. Semester 4 takes 5. Six courses fit in four semesters, because courses that are ready at the same time share a semester.
Course 2 needs 1, course 3 needs 2 and course 1 needs 3. Nothing can be taken first, so the answer is -1.
- • Courses are labelled 1 to n.
- • Each relation is [prevCourse, nextCourse], with both labels in that range.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Each semester, scan every course and take the ready ones; stop when none is ready
Process the ready courses one semester at a time; the number of semesters is the answer
Keep track of the taken courses. Each semester, scan every course that is not taken. A course is ready when all its prerequisites were taken in an earlier semester. Take all the ready courses together, but only after the scan finishes. Count the semesters. If a semester takes nothing while courses are left, return -1.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Topological Sort translate into production architectures and low-level memory mechanics.