#146 · Graphs · Advanced · 135 XP · about 25 min
A school offers n courses, numbered 0 to n - 1. Each rule [a, b] in rules says course a must be finished before course b can start, and you take one course at a time. Write course_order(n, rules) that returns a list of all n courses in an order that follows every rule.
Many orders may work, so use this tie-break: whenever several courses are ready to take, take the one with the smallest number. If the rules go round in a circle and no order works, return [].
course_order(4, [[0, 1], [0, 2], [1, 3], [2, 3]]) # returns [0, 1, 2, 3] course_order(3, [[2, 0], [1, 0]]) # returns [1, 2, 0] course_order(2, [[0, 1], [1, 0]]) # returns []
In the second example courses 1 and 2 are both ready at the start, so 1 comes first, then 2, and only then is course 0 ready. In the third, each course waits for the other, so neither can ever start.
1 <= n <= 2000, with up to 5,000 rules.[a, a] means a course waits for itself, so no order exists.Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.