4 min readRishi

Course Schedule: Topological Sort Detects the Cycle

In this series: Interview patterns in Python

Course Schedule: Topological Sort Detects the Cycle

Course Schedule asks whether you can finish numCourses courses given prerequisite pairs [a, b] meaning "b before a." It is a directed graph. An edge b → a means b must come first. You can finish if and only if the graph has no cycle.

Interviewers are not asking you to print a schedule. They are asking whether you notice a cycle, and whether you can say so without hand-waving DFS colors you do not finish writing.

This is one of a small set of interview-pattern notes I am keeping public. The rest of the old LeetCode dump is unpublished.

Kahn's algorithm

Count how many prerequisites each course still has. Every course with indegree 0 is ready. Take one, reduce the indegree of what depends on it, and repeat. If you process every course, there was no cycle. If some remain with indegree above 0, those are stuck in a cycle.

from collections import defaultdict, deque

def canFinish(numCourses: int, prerequisites: list[list[int]]) -> bool:
    indegree = [0] * numCourses
    graph = defaultdict(list)
    for course, prereq in prerequisites:
        graph[prereq].append(course)
        indegree[course] += 1

    ready = deque(i for i in range(numCourses) if indegree[i] == 0)
    taken = 0
    while ready:
        prereq = ready.popleft()
        taken += 1
        for course in graph[prereq]:
            indegree[course] -= 1
            if indegree[course] == 0:
                ready.append(course)
    return taken == numCourses

Time is O(V + E). Space is O(V + E) for the adjacency list and the queue. V is numCourses. E is the number of pairs.

Edge direction is the usual off-by-one. The pair is [course, prereq]. The edge is prereq → course. If you append the other way, indegree counts the wrong end and a valid chain looks cyclic (or the reverse). Write one example on the board: numCourses = 2, [[1, 0]] means take 0 then 1. Indegree of 1 is 1. Ready starts with [0]. After popping 0, indegree of 1 becomes 0. taken == 2.

The case they add if you go quiet

A self-loop, [0, 0], is a cycle of one. Indegree of 0 starts at 1, nothing is ready that can unlock it, taken stays short of numCourses. You do not need a special case.

Two nodes pointing at each other, and a third course with no edges, must return false. The isolated course is taken. The pair is not. Counting only the isolated node and returning true is the off-by-one people ship when they return taken > 0.

Empty prerequisites is true for any numCourses >= 0. Every indegree is 0, the queue holds every course, taken matches.

Duplicate pairs: if the input can repeat [1, 0], indegree of 1 becomes 2 and you need two pops of 0 to unlock it — but 0 is only processed once. Clarify. The LeetCode problem's pairs are unique. If the interviewer allows duplicates, either dedupe or store multi-edges consistently on both the list and the indegree.

Course Schedule II

Course Schedule II asks for one valid order. Same loop. Append prereq to an output list as you pop it. If taken != numCourses, return an empty list. The order you appended is one topological order, not the only one. Say that. Interviewers who want a specific order will add a tie-break (smallest index first: use a heap instead of a deque). Do not invent one.

def findOrder(numCourses: int, prerequisites: list[list[int]]) -> list[int]:
    indegree = [0] * numCourses
    graph = defaultdict(list)
    for course, prereq in prerequisites:
        graph[prereq].append(course)
        indegree[course] += 1

    ready = deque(i for i in range(numCourses) if indegree[i] == 0)
    order: list[int] = []
    while ready:
        course = ready.popleft()
        order.append(course)
        for nxt in graph[course]:
            indegree[nxt] -= 1
            if indegree[nxt] == 0:
                ready.append(nxt)
    return order if len(order) == numCourses else []

DFS colors, if they ask

Three states: 0 unvisited, 1 on the stack, 2 done. A neighbor that is 1 is a back edge — a cycle. A neighbor that is 2 is already finished; skip it. Recurse on 0. Kahn's algorithm is easier to finish on a whiteboard because the queue is the whole story. Use DFS if you are already comfortable and can explain the back-edge sentence in one breath.

Do not mix the two mid-answer. Pick one, write the base cases, then the loop.

Keep reading

Newsletter

New posts, straight to your inbox

One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.

Comments

  • No comments yet. Be the first.