You get numCourses courses, numbered 0 to numCourses - 1. You also get a list prerequisites of pairs [a, b]. A pair means you must finish course b before you start course a.
Return True if you can take all the courses in some order. If you can't, return False.
Example 1:
Input: numCourses = 5, prerequisites = [[1, 0], [2, 1], [4, 3], [4, 2]]
Output: True
Explanation: Each arrow goes from a course to a course that needs it:
0 → 1 → 2 → 4
3 → 4
Course 4 needs both 2 and 3.
Taking the courses in number order, from 0 to 4, works.
Example 2:
Input: numCourses = 4, prerequisites = [[1, 0], [2, 1], [3, 2], [1, 3]] Output: False Explanation: The arrows 1 → 2 → 3 → 1 form a loop. Course 1 waits for course 3. Course 3 waits for course 2. Course 2 waits for course 1. Course 0 is fine, but the other three can never start.
Example 3:
Input: numCourses = 3, prerequisites = [] Output: True Explanation: No course has a prerequisite, so any order works.
Constraints:
- 1 to 100,000 courses.
- Up to 100,000 pairs.
- Both courses in a pair are valid course numbers.
- The two courses in a pair are different.
- No pair appears twice.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
