L3 · FAANGGraphs~18 min · 6 tests

Course Schedule (Topological Sort)

Decide whether all courses can be finished given prerequisites by detecting a cycle with Kahn's topological sort in O(V + E). Asked at Amazon and Google.

The problem

There are n courses 0..n-1. prereqs is a list of pairs [a, b] meaning to take a you must first take b. Return True if every course can be finished (no cycle).

Examples

  1. Example 1

    Input

    can_finish(2, [[1, 0]])

    Expected output

    True
  2. Example 2

    Input

    can_finish(2, [[1, 0], [0, 1]])

    Expected output

    False

+ 4 hidden tests on Submit — 3-cycle, diamond, self-loop.

Edge cases to ask about

  • Self-loop
  • Disconnected courses
  • No prerequisites

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · can_finish
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    Measure it

    Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    DFS with three coloursO(V + E)O(V + E)A back-edge to a 'visiting' node is a cycle.
    bestKahn's algorithm (BFS on in-degrees)O(V + E)O(V + E)If you can't take every course, the rest form a cycle.
    Walkthrough of the optimal approach (try it yourself first)

    Model it as a directed graph and ask whether it has a cycle. Kahn's algorithm: start with every course whose in-degree is 0, take it, decrement the in-degree of its dependants, and enqueue any that drop to 0. If you take all n, there is no cycle; otherwise the leftovers are stuck in one.

    The order you take them in is a topological order — the follow-up asks you to return it.

    Complexity: O(V + E) time, O(V + E) space. Building the graph and processing every node and edge once.

    Reveal the reference solution
    from collections import deque
    
    def can_finish(n, prereqs):
        graph = [[] for _ in range(n)]
        indegree = [0] * n
        for course, before in prereqs:
            graph[before].append(course)
            indegree[course] += 1
        queue = deque(i for i in range(n) if indegree[i] == 0)
        taken = 0
        while queue:
            node = queue.popleft()
            taken += 1
            for nxt in graph[node]:
                indegree[nxt] -= 1
                if indegree[nxt] == 0:
                    queue.append(nxt)
        return taken == n

    Follow-ups interviewers ask

    • Return a valid order (Course Schedule II).
    • Detect the cycle with DFS colours.

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Course Schedule (Topological Sort) in Python?

    The optimal solution runs in O(V + E) time and O(V + E) auxiliary space. Building the graph and processing every node and edge once.

    What is the brute-force approach, and how do you optimise it?

    DFS with three colours: O(V + E) time, O(V + E) space. A back-edge to a 'visiting' node is a cycle. Kahn's algorithm (BFS on in-degrees): O(V + E) time, O(V + E) space. If you can't take every course, the rest form a cycle.

    What follow-up questions do interviewers ask about Course Schedule (Topological Sort)?

    Return a valid order (Course Schedule II). Detect the cycle with DFS colours.