Practice Problem
Course Schedule
Difficulty: Medium
Given a number of courses and their prerequisites, determine if it is possible to finish all courses (detect if the dependency graph has a cycle).
Course Schedule
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.
For example, the pair [0, 1] indicates that to take course 0 you must first take course 1.
Return true if you can finish all courses. Otherwise, return false.
Examples
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: You can take course 0 first, then course 1.Example 2:
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: Course 0 requires course 1 and course 1
requires course 0. This creates a cycle, making it
impossible to finish both.Example 3:
Input: numCourses = 3, prerequisites = [[1,0],[2,1]]
Output: true
Explanation: Take course 0, then 1, then 2.Constraints
1 <= numCourses <= 20000 <= prerequisites.length <= 5000prerequisites[i].length == 20 <= ai, bi < numCourses- All prerequisite pairs
prerequisites[i]are distinct.
Expected Complexity
- Time: O(V + E) where V = numCourses and E = number of prerequisites
- Space: O(V + E) for the adjacency list and tracking arrays
MEDIUM
Graphs
Topological Sort
DFS
BFS
Directed Graphs
Cycle Detection
Intermediate
0 views
Solution
Hints
Hint 1
Hint 2
Premium
Hint 3
Premium
Hint 4
Premium
This section is available for CodeSnatch Premium members only.
