Can Every Course Be Taken
A school offers n courses, numbered from 0 to n − 1. Some courses have prerequisites, given as two lists of the same length: course course[i] can only be taken after course before[i] has been taken.
Return true if there is an order in which every course can be taken, and false if not, which happens when some courses wait for each other in a circle.
Examples
n = 2, course = [1], before = [0] → true
n = 2, course = [1, 0], before = [0, 1] → false
n = 4, course = [1, 2, 3, 3], before = [0, 0, 1, 2] → true
n = 3, course = [0, 1, 2], before = [1, 2, 0] → falseIn the third example the order 0, 1, 2, 3 works. In the last, course 0 waits for 1, 1 waits for 2 and 2 waits for 0, so none of them can ever be first.
Constraints
- Between 1 and 10,000 courses and up to 20,000 prerequisites; every number is between
0andn − 1. A prerequisite may be listed twice, and a course may list itself, which it can then never take. - Aim for O(n + m), n courses and m prerequisites.
Console
›Run to see what your code prints
Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.
Expected is the reference solution's answer, from the judge. An input that breaks the statement's other rules may get any answer.