const solve = (nums) => { let left = 0, right = nums.length - 1; while (left < right) { const sum = nums[left] + nums[right]; if (sum === target) return [left, right]; }}
Problem Walkthrough

Course Schedule LeetCode Solution: Complete Walkthrough

Course Schedule (#207) is the gateway to topological sort — learn to model prerequisites as a directed graph, detect cycles with BFS and DFS, and master a pattern used in build systems, task scheduling, and dependency resolution.

10 min read|

Course Schedule (#207): the gateway to topological sort

Model prerequisites as a graph, detect cycles, and learn dependency resolution

Course Schedule: The Gateway to Topological Sort

Course schedule leetcode (#207) is where most engineers first encounter topological sort in an interview context — and for good reason. It is one of the top 10 most frequently asked Medium graph problems, appearing consistently at Google, Amazon, Meta, and Microsoft. If you have never built a directed graph from scratch and checked it for cycles, this is the problem that teaches you how.

The beauty of Course Schedule is that it maps directly to real-world systems. Package managers resolve dependency graphs. Build tools like Make and Gradle schedule compilation order. CI/CD pipelines determine which jobs can run in parallel. Every one of these systems solves the same underlying problem: given a set of tasks with prerequisites, can you complete them all without hitting a circular dependency?

In this walkthrough, you will learn to model the problem as a directed graph, solve it with both BFS (Kahn's algorithm) and DFS (3-color marking), handle edge cases, and connect the pattern to follow-up problems like Course Schedule II (#210). By the end, topological sort will feel like second nature.

Understanding the Course Schedule Leetcode Problem

The problem gives you two inputs: numCourses (an integer representing courses labeled 0 to numCourses-1) and prerequisites (a list of pairs where [a, b] means "to take course a, you must first complete course b"). Your task is to return true if you can finish all courses, or false if you cannot.

The key insight is recognizing what makes it impossible to finish all courses: a circular dependency. If course A requires B, B requires C, and C requires A, no valid ordering exists. This means the problem reduces to a single question — does the prerequisite graph contain a cycle?

Restated in graph terminology: each course is a node, each prerequisite pair [a, b] creates a directed edge from b to a (b must come before a), and "can you finish all courses?" is equivalent to asking "is this a Directed Acyclic Graph (DAG)?" If yes, a topological ordering exists and you return true. If a cycle exists, you return false.

  • Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
  • Graph: 0 -> 1, 0 -> 2, 1 -> 3, 2 -> 3
  • Output: true — a valid order is [0, 2, 1, 3] or [0, 1, 2, 3]
  • Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
  • Graph: 0 -> 1, 1 -> 0 (cycle!)
  • Output: false — course 0 and course 1 depend on each other
ℹ️

Did You Know

Course Schedule (#207) is one of the top 10 most frequently asked Medium graph problems — it appears at Google, Amazon, Meta, and Microsoft, often as a warm-up before harder graph questions.

Model Prerequisites as a Directed Graph

Before choosing an algorithm, you need to build the graph. For the course schedule leetcode problem, you will use an adjacency list representation. Create an array of length numCourses where each index holds a list of courses that depend on the course at that index. For each prerequisite pair [a, b], add a to the adjacency list of b — meaning "after finishing b, you can take a."

You also need an in-degree array. The in-degree of a node is the number of edges pointing into it — in other words, the number of prerequisites that course has. Initialize an array of length numCourses with all zeros, then for each pair [a, b], increment inDegree[a] by one.

This two-structure setup — adjacency list plus in-degree array — is the foundation for Kahn's BFS algorithm. For the DFS approach, you only need the adjacency list, but having both ready gives you flexibility. Building the graph takes O(E) time where E is the number of prerequisite pairs, and O(V + E) space for the adjacency list.

  • Adjacency list: array of arrays, where graph[i] lists all courses that require course i
  • In-degree array: inDegree[i] = number of prerequisites course i has
  • Build time: O(E) where E = number of prerequisite pairs
  • Space: O(V + E) where V = numCourses

Approach 1: BFS with Kahn's Algorithm

Kahn's algorithm is the most intuitive approach to topological sort. The idea is simple: start with all courses that have no prerequisites (in-degree = 0), process them, reduce the in-degree of their dependents, and repeat. If you process all courses, the graph is a DAG. If some courses remain unprocessed, a cycle exists.

Start by adding every node with in-degree 0 to a queue — these are courses with no prerequisites that you can take immediately. Then enter the BFS loop: dequeue a course, increment your processed count, and for each course that depends on it, decrement that course's in-degree by one. If any dependent's in-degree drops to 0, add it to the queue.

When the queue empties, check whether you processed all numCourses nodes. If processedCount equals numCourses, return true — every course can be completed. If processedCount is less than numCourses, the remaining courses are trapped in a cycle and cannot be scheduled. The time complexity is O(V + E) because you visit every node and edge exactly once.

  1. 1Build adjacency list and in-degree array from prerequisites
  2. 2Initialize a queue with all nodes where inDegree[i] === 0
  3. 3While the queue is not empty: dequeue a node, increment processedCount, and for each neighbor, decrement its in-degree. If the neighbor's in-degree hits 0, enqueue it
  4. 4Return processedCount === numCourses
💡

Pro Tip

Kahn's algorithm naturally tells you if there's a cycle — if the count of processed nodes is less than numCourses, a cycle exists. No need for separate cycle detection code.

Approach 2: DFS with 3-Color Marking

The DFS approach to the course schedule leetcode problem uses a 3-color state machine to detect back edges — which indicate cycles. Each node starts as WHITE (unvisited). When you begin exploring a node, mark it GRAY (currently in the recursive call stack). When you finish exploring all its descendants, mark it BLACK (fully processed).

The cycle detection rule is straightforward: if during DFS you encounter a GRAY node, you have found a back edge — a path that leads from a node back to one of its own ancestors. This means a cycle exists and you should return false immediately. BLACK nodes are safe to skip because they and all their descendants have already been fully explored with no cycles found.

Implement this by iterating through all nodes 0 to numCourses-1. For each WHITE node, run DFS. In the DFS function, mark the node GRAY, recurse on all neighbors, and if any recursive call detects a cycle, propagate false upward. If all neighbors return true (no cycle), mark the node BLACK and return true. Like BFS, the time complexity is O(V + E).

  • WHITE (0): unvisited — has not been explored yet
  • GRAY (1): in progress — currently on the DFS call stack
  • BLACK (2): fully processed — all descendants explored, no cycle found
  • GRAY -> GRAY edge: back edge detected, cycle exists, return false

Edge Cases and Follow-Up Problems

Several edge cases are worth testing before submitting. If prerequisites is empty, every course is independent and the answer is always true. If numCourses is 1, there can be no prerequisites (or only a self-loop), so return true unless a self-loop exists. Self-loops like [0, 0] create a trivial cycle — both BFS and DFS handle this correctly without special-case code.

The natural follow-up is Course Schedule II (#210), which asks you to return the actual topological order instead of just true/false. With Kahn's algorithm, this is trivial — just record the order in which nodes are dequeued. With DFS, push nodes onto a result stack when they are marked BLACK, then reverse the stack at the end.

Other related problems include Parallel Courses (#1136), which asks for the minimum number of semesters to complete all courses (the longest path in the DAG), and Alien Dictionary (#269), which uses topological sort to derive character ordering from a list of words. Once you internalize the course schedule pattern, these follow-ups become manageable extensions rather than entirely new problems.

  • Course Schedule II (#210): return the topological order, not just true/false
  • Parallel Courses (#1136): find the minimum semesters (longest path in DAG)
  • Alien Dictionary (#269): derive character order via topological sort
  • All follow-ups build on the same prerequisite graph + cycle detection foundation
⚠️

Watch Out

The 3-color DFS approach is elegant but error-prone — forgetting to mark nodes as black (fully processed) leads to false cycle detection. Always complete the white->gray->black state machine.

What Course Schedule Teaches You

Course Schedule (#207) is more than a single problem — it is a template for an entire class of dependency-resolution questions. The core skill you develop is graph modeling: taking a real-world scenario with tasks and prerequisites and translating it into nodes and directed edges. This same skill applies to build systems, package managers, workflow engines, and any system that needs to resolve ordering constraints.

You also learn two fundamental graph algorithms — BFS topological sort (Kahn's) and DFS cycle detection (3-color) — that appear in dozens of other problems. Kahn's algorithm is especially versatile because it naturally produces the topological order, detects cycles, and can be extended to compute the longest path in a DAG.

If you are preparing for coding interviews, make course schedule leetcode a priority. Practice it until you can implement both approaches from memory in under 15 minutes, then move on to Course Schedule II and Parallel Courses. Use YeetCode flashcards to drill the pattern — recognizing "prerequisites = directed graph = topological sort" should become automatic.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now