Tutorialspoint
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)
GraphAlgorithmsFacebookZomato
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Create an adjacency list representation of the directed graph.
 Step 2: Initialize a visited array to track nodes' states (0: not visited, 1: being visited, 2: completely visited).
 Step 3: For each course, perform DFS if it hasn't been visited yet.
 Step 4: During DFS, mark current node as "being visited" (1).
 Step 5: If any neighbor is marked as "being visited", a cycle exists, return false.
 Step 6: After visiting all neighbors, mark current node as "completely visited" (2).
 Step 7: If no cycles are detected, return true.

Submitted Code :