Course Schedule

Determine if you can finish all courses given prerequisites.

Pattern

Topological Sort / Cycle Detection

This problem follows the Topological Sort / Cycle Detection pattern, commonly found in the Graphs category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Build adjacency list. DFS with 3 states (unvisited, visiting, visited). Detect cycles.

Key Insight

Three states (not just visited/unvisited) are needed to detect back edges in directed graphs — 'visiting' means the node is in the current DFS path.

Step-by-step

  1. 1Build an adjacency list from the prerequisites
  2. 2Use DFS with 3 states: unvisited (0), visiting (1), visited (2)
  3. 3If you encounter a 'visiting' node during DFS, there's a cycle
  4. 4If all nodes can be visited without cycles, return true

Pseudocode

graph = defaultdict(list)
for a, b in prerequisites:
    graph[a].append(b)
state = [0] * numCourses  # 0=unvisited, 1=visiting, 2=visited
def dfs(course):
    if state[course] == 1: return false  # cycle
    if state[course] == 2: return true   # done
    state[course] = 1
    for prereq in graph[course]:
        if not dfs(prereq): return false
    state[course] = 2
    return true
return all(dfs(i) for i in range(numCourses))
Complexity Analysis

Time Complexity

O(V + E)

Space Complexity

O(V + E)
More Graphs Problems

Master this pattern with YeetCode

Practice Course Schedule and similar Graphs problems with flashcards. Build pattern recognition through active recall.

Practice this problem