Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Topological Sort High frequency Solution Available Practice Mode

Course Schedule LeetCode Solution

Tags: #Graph #DFS #BFS #Topological Sort

Approach Summary

Detect cycle in directed graph using DFS (3-color states) or Kahn's BFS topological sort. If cycle exists, impossible.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Topological Sort Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Topological Sort pattern.

Framework: Topological Sort • Interview Prep: Tested at FAANG • Explore all Topological Sort problems & invariants →

How to Recognize This Pattern

  • Prerequisite ordering
  • Can all courses be taken?

Complexity Analysis

Time Complexity

O(V + E)

Space Complexity

O(V + E)

Tags

Graph DFS BFS Topological Sort

Frequently Asked Questions

What is the optimal time and space complexity for Course Schedule?
The optimal solution for Course Schedule achieves O(V + E) runtime complexity and requires O(V + E) auxiliary space. Time Complexity is O(V + E) where V = numCourses and E = prerequisites.length. Constructing the adjacency list and in-degree array takes O(V + E), and every node and edge is processed at most once during traversal. Space Complexity is O(V + E) to store the adjacency list graph representation, in-degree counts, and traversal queue/stack.
How do I identify that Course Schedule requires the Topological Sort pattern?
In technical interviews, look for key problem signals: Prerequisite ordering; Can all courses be taken?. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Topological Sort strategy.
What critical edge cases must be handled in Course Schedule?
Essential edge cases to verify include: No prerequisites (prerequisites is empty) — all courses can be finished immediately, return true; Self-dependency [0, 0] — immediate cycle of length 1, return false; Mutual dependency [0, 1] and [1, 0] — 2-cycle, return false; Disconnected components — multiple independent sets of courses, all must be cycle-free. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Course Schedule?
Course Schedule is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Amazon, Facebook, Google, Zenefits.
Buy me a coffee
Daily Practice
0/0