progress

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

Course Schedule

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 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.

⭐ Bonus: a speed test with a 100,000-long chain earns a star in O(V + E) without recursing along it (that overflows Python's limit of about 1,000 frames).

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