Practice · Topological sort · 1 of 2

Can Every Course Be Taken?

There are numCourses courses, numbered from 0 to numCourses − 1. Each pair [a, b] in prerequisites means you must finish course b before you can take course a.

Return true if there is an order in which you can take every course, and false if the prerequisites make that impossible.

Example 1

Input
numCourses = 4, prerequisites = [[2, 0], [2, 1], [3, 2]]
Output
true
Take 0 and 1, then 2, then 3.

Example 2

Input
numCourses = 3, prerequisites = [[0, 1], [1, 2], [2, 0]]
Output
false
0 waits for 1, 1 waits for 2, and 2 waits for 0, so none of them can go first.

Constraints

  • 1 ≤ numCourses ≤ 2000
  • prerequisites holds at most 5000 pairs, each of two different courses, with no pair repeated.