</>

207. Course Schedule

Medium NeetCode 150
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Graphs
Time
—
Space
—

Standard Solution (C++)

SummaryGiven a list of prerequisite pairs, determine whether it is possible to complete all courses — equivalently, check whether the directed dependency graph contains no cycle.

Approach
  • Model courses as nodes in a directed graph where an edge a -> b means course a must be taken before b.
  • Use Kahn's algorithm (BFS topological sort): repeatedly process nodes with in-degree zero, decrementing the in-degree of their neighbors.
  • If every course can be processed (total count equals numCourses), no cycle exists and all courses can be finished; otherwise a cycle blocks completion.
  • This works because a cycle creates a set of nodes whose in-degrees never reach zero, preventing them from being enqueued.
#include <vector>
#include <queue>
using namespace std;

class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        // Build adjacency list and compute in-degrees.
        vector<vector<int>> adj(numCourses);
        vector<int> inDegree(numCourses, 0);

        for (const auto& edge : prerequisites) {
            int course = edge[0], prereq = edge[1];
            adj[prereq].push_back(course); // prereq -> course
            ++inDegree[course];
        }

        // Seed BFS with all courses that have no prerequisites.
        queue<int> q;
        for (int i = 0; i < numCourses; ++i) {
            if (inDegree[i] == 0) q.push(i);
        }

        // Kahn's algorithm: process nodes layer by layer.
        int finished = 0;
        while (!q.empty()) {
            int cur = q.front(); q.pop();
            ++finished;
            for (int next : adj[cur]) {
                if (--inDegree[next] == 0) q.push(next);
            }
        }

        // A cycle prevents some nodes from ever reaching in-degree 0.
        return finished == numCourses;
    }
};
Time O(V + E) where V = numCourses and E = number of prerequisite pairs Space O(V + E) for the adjacency list and in-degree array

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <vector>
#include <queue>
using namespace std;

class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        // topological sort
        // 1. create adj list
        // 2. start from indegree=0, check if I can go through all the courses

        vector<vector<int>> adj(numCourses);
        vector<int> inDegree(numCourses, 0);

        for(const auto& p: prerequisites){
            // [course, its prereq]
            adj[p[1]].push_back(p[0]); // take i first, so that we can consider adj[i]
            ++inDegree[p[0]];
        }

        queue<int> q; // record those courses with inDegree=0
        for(int i=0; i<numCourses; ++i){
            if(inDegree[i]==0){
                q.push(i);
            }
        }

        int count=0;

        while(!q.empty()){
            int qlen=q.size();
            count+=qlen;

            for(int i=0; i<qlen; ++i){
                int cur=q.front();
                q.pop();
                for(const int v: adj[cur]){ // vertex in adj[cur]
                    --inDegree[v];
                    if(inDegree[v]==0){
                        q.push(v);
                    }
                }
            }
        }

        return count==numCourses;
    }
};

// Time: O(V+E) where V is the number of courses and E is the number of prerequisites
// Space: O(V+E) for the adjacency list and inDegree array

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern