Skip to content
BytePatterns

Course Order Feasibility

MediumGraphs#topological-sort#cycle-detection~35m

Problem

A programme has n courses numbered from 0, plus a list of pairs where the pair course, before means that course cannot be taken until before is finished. Decide whether an order exists that lets a student finish all n courses. Return true when such an order exists and false when the requirements contradict each other.

Examples

Input:  n = 3, pairs = [[1, 0], [2, 1]]
Output: True
Why:    the order 0, 1, 2 satisfies both requirements
Input:  n = 2, pairs = [[1, 0], [0, 1]]
Output: False
Why:    each course waits for the other, so neither can start
Input:  n = 1, pairs = []
Output: True
Why:    edge case, a course with no requirements can always be taken

Hints

0 / 3

Stuck on the idea rather than the code? Topological Sort covers it.