Graphs · Problem 2 of 3

Can every course be completed?

Pattern: Course Schedule: Detect a Cycle

mediumNot solved yet

The problem

An online school has courses numbered 0 to courses - 1. Each pair [a, b] in prereqs means course b must be finished before course a. Write a function that returns whether a student could finish every course in some order.

text
1can_finish_all(3, [[1, 0], [2, 1]])          ->  True
2can_finish_all(2, [[0, 1], [1, 0]])          ->  False
3can_finish_all(4, [[1, 0], [2, 1], [0, 2]])  ->  False
Example 1 (possible) and example 3 (a loop)
012012

An arrow means "unlocks". On the right, each course waits for another in the loop, so none can start.

The first is possible in the order 0, 1, 2. In the second, each course waits for the other. In the third, 0 → 1 → 2 → 0 is a loop, so none of those three can start.

Write can_finish_all(courses, prereqs) in Python or canFinishAll(courses, prereqs) in JavaScript. Examples are written in Python: in JavaScript, None is null and True / False are true / false.

Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Write your function, then run it against 20 tests.

Breakdown

Stuck? Reveal one step at a time, and try again after each one.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.