Skip to main content
Back to problems
Leetcode
Medium
Graphs
Google
Meta
Microsoft
Course Schedule

Determine whether all courses can be finished given prerequisite constraints.

Acceptance 0%
Problem Statement

Course Schedule

You are given nn courses labeled from $0toton - 1$ and a list of prerequisite pairs. Each pair indicates that one course must be completed before another course can be taken.

Return true if it is possible to finish every course. Otherwise, return false.

The prerequisite relationships form a directed graph. Your task is to determine whether that graph contains a cycle.

Input Format

  • An integer n, the number of courses.
  • A list of pairs prerequisites, where each pair [a, b] means course b must be taken before course a.

Output Format

  • Return a boolean value:
    • true if all courses can be completed.
    • false if the prerequisite graph has a cycle.

Constraints

  • 1n1 \le n
  • prerequisites[i] contains exactly two integers.
  • Each course index is in the range [0, n - 1].
  • A course may appear in multiple prerequisite relations.

Hints

  • Think of each prerequisite as a directed edge.
  • If there is a directed cycle, no valid course order exists.
  • You can solve this with either topological sorting or DFS-based cycle detection.
Examples
Sample cases returned by the problem API.

Example 1

Input

n = 2, prerequisites = [[1,0]]

Output

true

Explanation

Course 0 can be taken first, then course 1.

Example 2

Input

n = 2, prerequisites = [[1,0],[0,1]]

Output

false

Explanation

The two courses depend on each other, so a cycle exists.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.