~/problems / Graphs / Topological sort (Kahn's)

Course Schedule

easy ~15 min

There are num_courses courses labelled 0 .. num_courses - 1. Each pair [a, b] in prerequisites means course b must be taken before course a.

Write can_finish(num_courses, prerequisites) -> bool that returns True if some ordering lets you take every course, and False otherwise (that is, when the prerequisite graph has a cycle).

can_finish(3, [[1, 0], [2, 1]])          # True  (0, then 1, then 2)
can_finish(3, [[1, 0], [0, 2], [2, 1]])  # False (0 -> 1 -> 2 -> 0 is a cycle)
can_finish(4, [])                        # True

Constraints: up to 100,000 courses and 100,000 pairs; pairs can repeat. Aim for O(V + E). The tests include a 100k-long chain, which overflows Python's recursion limit (about 1,000 frames) if you recurse along it.

Show hint

Some course must have no prerequisites at all. Take it, cross it off everyone's list, and repeat; notice what happens when you get stuck.

Topic: Topological sort (Kahn's). BFS over in-degree-0 nodes; leftover nodes mean a cycle.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc