Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #207: Course Schedule

In this guide, we solve Leetcode #207 Course Schedule in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Depth-First Search, Breadth-First Search, Graph, Topological Sort

Intuition

The data forms a graph, so we should explore nodes and edges systematically.

A traversal ensures we visit each node once while maintaining the needed state.

Approach

Build an adjacency list and traverse with BFS or DFS.

Aggregate results as you visit nodes.

Steps:

  • Build the graph.
  • Traverse with BFS/DFS.
  • Accumulate the required output.

Example

Input: numCourses = 2, prerequisites = [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

Python Solution

class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: g = [[] for _ in range(numCourses)] indeg = [0] * numCourses for a, b in prerequisites: g[b].append(a) indeg[a] += 1 q = [i for i, x in enumerate(indeg) if x == 0] for i in q: numCourses -= 1 for j in g[i]: indeg[j] -= 1 if indeg[j] == 0: q.append(j) return numCourses == 0

Complexity

The time complexity is O(n+m)O(n + m)O(n+m), and the space complexity is O(n+m)O(n + m)O(n+m). The space complexity is O(n+m)O(n + m)O(n+m).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy