
Problem
Solution
Submissions
Course Schedule
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C# program to determine if it's possible to finish all the courses. You are given a total of numCourses
and an array prerequisites
where prerequisites[i] = [ai, bi]
indicates that you must take course bi
first if you want to take course ai
. Return true
if you can finish all courses, or false
otherwise.
Example 1
- Input: numCourses = 2, prerequisites = [[1,0]]
- Output: true
- Explanation:
- There are 2 courses to take.
- To take course 1, you need to have finished course 0.
- So it's possible.
Example 2
- Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
- Output: false
- Explanation:
- There are 2 courses to take.
- To take course 1, you need to finish course 0.
- To take course 0, you need to finish course 1.
- This creates a cycle, making it impossible to finish all courses.
Constraints
- 1 <= numCourses <= 2000
- 0 <= prerequisites.length <= 5000
- prerequisites[i].length == 2
- 0 <= ai, bi < numCourses
- All the pairs [ai, bi] are distinct
- Time Complexity: O(V + E) where V is the number of vertices and E is the number of 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 the problem as a directed graph where each course is a vertex and prerequisites are edges
- Use Depth-First Search (DFS) or Breadth-First Search (BFS) to detect cycles in the graph
- If a cycle exists, it's impossible to complete all courses
- Use a visited array to keep track of visited vertices
- Use another array to keep track of vertices in the current DFS path