
Problem
Solution
Submissions
Course Schedule
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C program to determine if you can finish all courses given the course 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.
Example 1
- Input: numCourses = 2, prerequisites = [[1,0]]
- Output: true
- Explanation:
- There are 2 courses to take.
- To take course 1 you should have finished course 0.
- This forms a valid dependency: 0 -> 1.
- No cycle exists, so all courses can be completed.
- There are 2 courses to take.
Example 2
- Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
- Output: false
- Explanation:
There are 2 courses to take.- To take course 1 you should have finished course 0.
- To take course 0 you should have finished course 1.
- This creates a circular dependency: 0 -> 1 -> 0.
- Due to the cycle, it's impossible to finish all courses.
- To take course 1 you should have finished course 0.
Constraints
- 1 ≤ numCourses ≤ 2000
- 0 ≤ prerequisites.length ≤ 5000
- prerequisites[i].length == 2
- 0 ≤ ai, bi < numCourses
- Time Complexity: O(V + E) where V is vertices and E is edges
- 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
- Model this as a directed graph cycle detection problem.
- Use DFS with three states: unvisited, visiting, and visited.
- Create an adjacency list to represent the course dependencies.
- For each unvisited course, perform DFS to detect cycles.
- If during DFS you encounter a node in "visiting" state, there's a cycle.
- Use a color array: 0 = unvisited, 1 = visiting, 2 = visited.