iq.lab
Python starts when a code cell comes near or you run one
mediumTopological sort target 25 min

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.

Example 1
Inputnum_courses = 3, prerequisites = [[1, 0], [2, 1]]OutputTrue

Take 0, then 1, then 2.

Example 2
Inputnum_courses = 3, prerequisites = [[0, 1], [1, 2], [2, 0]]OutputFalse

0 waits for 1, 1 waits for 2, and 2 waits for 0. None of them can go first.

Example 3
Inputnum_courses = 4, prerequisites = [[1, 0], [2, 3], [3, 2]]OutputFalse

0 and 1 are fine, but 2 and 3 each wait for the other. One loop anywhere is enough to fail.

Constraints
  • 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.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.