You are given an integer numCourses representing the number of courses labeled from 0 to numCourses - 1. You are also given a list prerequisites where each entry [a, b] means you must complete course b before you are allowed to take course a.
Decide whether it is possible to finish every course. Return true if a valid order of study exists, and false otherwise.
The answer is false exactly when the prerequisite relationships form a cycle, because a cycle would force a course to depend on itself either directly or indirectly.
Example 1
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
There are two courses. Course 1 depends on course 0, so the order 0 then 1 finishes everything.
Example 2
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Course 1 needs course 0 and course 0 needs course 1. This circular dependency makes both impossible.
Constraints
1 <= numCourses <= 20000 <= prerequisites.length <= 5000prerequisites[i].length == 20 <= a_i, b_i < numCoursesAll the pairs prerequisites[i] are unique.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI