Tutorialspoint
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.
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.
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)
GraphAlgorithmsIBMEY
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 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.

Steps to solve by this approach:

 Step 1: Create an adjacency list representation of the course dependency graph.

 Step 2: Initialize a color array to track node states (unvisited=0, visiting=1, visited=2).
 Step 3: For each unvisited course, start a DFS traversal.
 Step 4: Mark the current course as "visiting" (color = 1) when entering DFS.
 Step 5: For each dependent course, check if it's already in "visiting" state.
 Step 6: If a "visiting" node is encountered, a cycle exists - return false.
 Step 7: Mark the course as "visited" (color = 2) when DFS completes successfully.

Submitted Code :