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 II LeetCode Solution

Tags: #Graph #DFS #BFS #Topological Sort

Approach Summary

Kahn's algorithm: start with 0-in-degree nodes. Return ordering; if not all nodes processed, cycle exists.

Practice Mode

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

  • Return topological order of courses

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 II?
The optimal solution for Course Schedule II achieves O(V + E) runtime complexity and requires O(V + E) auxiliary space. Every edge is relaxed once — O(V + E) time. The adjacency list, indegree array, queue, and result use O(V + E) space.
How do I identify that Course Schedule II requires the Topological Sort pattern?
In technical interviews, look for key problem signals: Return topological order of courses. 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 II?
Essential edge cases to verify include: No prerequisites — any order is valid; the queue starts with all courses; A cycle — return []; Unreachable courses (no prerequisites and none depending on them) — they simply start in the queue; A single course — [0]. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Course Schedule II?
Course Schedule II is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Facebook, Amazon, Uber.
Buy me a coffee
Daily Practice
0/0