Can every course be finished
A school offers num_courses courses, numbered 0 to num_courses - 1. Each pair [a, b] in prerequisites means course b must be finished before course a can start. You take one course at a time.
Return True if some order lets you finish every course, and False if no order does. A pair can name the same course twice, such as [1, 1]: that course needs itself, so it can never start.
num_courses = 3, prerequisites = [[1, 0], [2, 1]]OutputTrueTake 0, then 1, then 2.
num_courses = 3, prerequisites = [[0, 1], [1, 2], [2, 0]]OutputFalse0 waits for 1, 1 waits for 2, and 2 waits for 0. None of them can go first.
num_courses = 4, prerequisites = [[1, 0], [2, 3], [3, 2]]OutputFalse0 and 1 are fine, but 2 and 3 each wait for the other. One loop anywhere is enough to fail.
1 ≤ num_courses ≤ 2 × 104
0 ≤ len(prerequisites) ≤ 2 × 104
0 ≤ a, b < num_courses
No pair appears twice.
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.