AceYourInterviews
Checking sign-in…

103. Course Schedule — Feasibility

IntermediateDAG feasibility with indegrees

A pair identifies a course and another course that must be taken first. Decide whether there is some way to finish all courses while obeying all prerequisite relationships.

The order of the pair matters. A cycle of prerequisites makes completion impossible, while courses with no prerequisites still need to be included.

Example 1

Input

numCourses=2, prerequisites=[[1,0]]

Output

true

Explanation: Finish 0, then 1.

Example 2

Input

numCourses=2, prerequisites=[[1,0],[0,1]]

Output

false

Explanation: Each course waits for the other.

Example 3

Input

numCourses=3, prerequisites=[[1,0],[1,0]]

Output

true

Explanation: Both parallel edges are removed when course 0 finishes; course 2 is independent.

Constraints

  • 0 <= numCourses <= 105
  • 0 <= edge occurrences <= 2 * 105
  • 0 <= vertex label < numCourses
Hints
Hint 1

Which courses can be taken before any others?

Hint 2

After taking one, which unmet counts change?

Hint 3

Repeatedly remove zero-indegree courses; success requires removing every vertex.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Parallel edges and an isolated course

3
[[1,0],[1,0]]
true