Python coding

Can you finish every course?

There are n courses numbered 0 to n - 1. Each pair [course, needs] in prereqs means you must finish needs before you start course. Return True if some order lets you finish every course, otherwise False.

A course can have several prerequisites, pairs may repeat, and prereqs may be empty.

Besides the tests, one large input (4,000 courses in a chain) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • can_finish(2, [[1,0]]) → true
  • can_finish(2, [[1,0],[0,1]]) → false
  • can_finish(4, [[1,0],[2,0],[3,1],[3,2]]) → true
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Model it as a directed graph with an edge needs → course. You can finish every course exactly when that graph has no cycle.

Hint 2

Count each course's in-degree. Queue the courses at 0; each time you take one, decrement its dependents and queue those that reach 0. Did you take all n?

Solution and why it works
pythonO(n + E), E = number of pairs · O(n + E)
from collections import deque

def can_finish(n: int, prereqs: list[list[int]]) -> bool:
    adj, indeg = [[] for _ in range(n)], [0] * n
    for course, needs in prereqs:
        adj[needs].append(course)
        indeg[course] += 1
    queue = deque(i for i in range(n) if indeg[i] == 0)
    taken = 0
    while queue:
        u = queue.popleft()
        taken += 1
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                queue.append(v)
    return taken == n

Kahn's algorithm only takes a course once all its prerequisites are taken. A course on a cycle, or one that depends on a cycle, never reaches in-degree 0, so taking fewer than n courses means it's impossible. Two traps: the pair [course, needs] is the edge needs → course, and a plain visited set is not a directed cycle check: a diamond (two paths to one course) would look like a cycle.