
Problem
Solution
Submissions
Course Schedule
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to determine if it's possible to finish all courses given prerequisites. 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. This is essentially detecting if there's a cycle in a directed graph.
Example 1
- Input: numCourses = 2, prerequisites = [[1,0]]
- Output: true
- Explanation:
- There are 2 courses to take (0 and 1).
- To take course 1, you must first take course 0.
- Course 0 has no prerequisites.
- Therefore, it's possible to complete all courses: 0 → 1.
- There are 2 courses to take (0 and 1).
Example 2
- Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
- Output: false
- Explanation:
- There are 2 courses to take (0 and 1).
- To take course 1, you must first take course 0.
- To take course 0, you must first take course 1.
- This creates a circular dependency (cycle).
- Therefore, it's impossible to complete all courses.
- There are 2 courses to take (0 and 1).
Constraints
- 1 ≤ numCourses ≤ 2000
- 0 ≤ prerequisites.length ≤ 5000
- prerequisites[i].length == 2
- 0 ≤ ai, bi < numCourses
- All the pairs prerequisites[i] are unique
- Time Complexity: O(V + E)
- Space Complexity: O(V + E)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Build an adjacency list representation of the directed graph from prerequisites
- Use DFS (Depth First Search) to detect cycles in the graph
- Maintain a visited array with three states: unvisited, visiting, and visited
- If during DFS you encounter a node that is currently being visited, there's a cycle
- Use topological sorting approach or cycle detection to solve the problem
- Return false if any cycle is detected, true otherwise