Skip to content

Conversation

@kavishnasta
Copy link

@kavishnasta kavishnasta commented Oct 19, 2025

  1. Course Schedule.cpp

Intuition

We have numCourses courses numbered from 0 to numCourses-1. The array prerequisites contains pairs [a, b], which means to take course a, you must finish course b first.

We can represent this as a directed graph: courses are nodes, and a prerequisite [a, b] is a directed edge from b to a, since b must come before a.

Instead of thinking about whether all courses can be completed, this transforms to: does this directed graph allow for a valid order to visit all nodes while respecting edges? In other words, is there a topological order for this graph?

If there is a cycle, like A → B → C → A, then you cannot complete the courses because each one depends on another in a loop. There is no starting node with an in-degree of 0.

We shall compute the in-degree, which is the number of incoming edges or prerequisites for every node. Then, you pick all nodes with an in-degree of zero, meaning these are the courses you can take right away. Remove them or mark them as done, and reduce the in-degree of their neighbors, which are the courses depending on them. Continue this until you either process all courses (good) or cannot make further progress while still having courses left (bad, indicating a cycle).

If we manage to process all numCourses courses using this method, we return true. If not, we return false.

The complexity is O(V + E), where V is the number of courses and E is the number of prerequisite pairs.

Key things to monitor include building the graph with the correct direction, ensuring the initial queue contains in-degree zero nodes, running the loop until the queue is empty, and keeping track of the number of processed courses.

Approach

1)Build an adjacency list. Graph[b] contains a if there is a prerequisite [a, b].

2)Create an array inDegree[a]++ for each [a, b].

3)Start a queue with all i such that inDegree[i]==0.

4)Remove one course u from the queue and increase the processed count. For each v in graph[u], reduce inDegree[v]. If inDegree[v] becomes 0 after decrementing, add v to the queue.

5)After the loop, if processed equals numCourses, return true; otherwise, return false.

Code Solution (C++)

    class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        vector<vector<int>> graph(numCourses);
        vector<int> inDegree(numCourses, 0);
        for (auto &p : prerequisites) {
            int a = p[0], b = p[1];
            graph[b].push_back(a);
            inDegree[a]++;
        }
        queue<int> q;
        for (int i = 0; i < numCourses; i++) {
            if (inDegree[i] == 0) q.push(i);
        }
        int processed = 0;
        while (!q.empty()) {
            int u = q.front();
            q.pop();
            processed++;
            for (int v : graph[u]) {
                inDegree[v]--;
                if (inDegree[v] == 0) {
                    q.push(v);
                }
            }
        }
        return processed == numCourses;
    }
};
    

Related Issues

Closes #190

By submitting this PR, I confirm that:

  • [✅] This is my original work not totally AI generated
  • [✅] I have tested the solution thoroughly on leetcode
  • [✅] I have maintained proper PR description format
  • [✅] This is a meaningful contribution, not spam

Summary by Sourcery

New Features:

  • Implement BFS-based topological sort solution in C++ to determine if all courses can be finished given prerequisites

@sourcery-ai
Copy link

sourcery-ai bot commented Oct 19, 2025

Reviewer's Guide

This PR introduces a new C++ solution for the Course Schedule problem using Kahn’s algorithm: it constructs a directed graph from prerequisites, tracks in-degrees, and performs a BFS-based topological sort to detect cycles and determine if all courses can be completed.

Class diagram for the new Solution class (Course Schedule)

classDiagram
class Solution {
  +bool canFinish(int numCourses, vector<vector<int>>& prerequisites)
}
class graph {
}
class inDegree {
}
class q {
}
Solution "canFinish()" --> graph : uses
Solution "canFinish()" --> inDegree : uses
Solution "canFinish()" --> q : uses
graph : vector<vector<int>>
inDegree : vector<int>
q : queue<int>
Loading

Flow diagram for Kahn's algorithm in Course Schedule solution

flowchart TD
    A["Start: Build graph and inDegree array"] --> B["Initialize queue with courses having inDegree 0"]
    B --> C["While queue is not empty"]
    C --> D["Pop course u from queue"]
    D --> E["Increment processed count"]
    E --> F["For each neighbor v of u in graph"]
    F --> G["Decrement inDegree[v]"]
    G --> H["If inDegree[v] == 0, add v to queue"]
    H --> C
    C --> I["After loop, check if processed == numCourses"]
    I --> J["Return true if all courses processed, else false"]
Loading

File-Level Changes

Change Details Files
Add BFS-based topological sort in canFinish
  • Build adjacency list from prerequisite pairs
  • Compute and store in-degree for each course
  • Enqueue courses with zero in-degree
  • Process queue: decrement neighbors’ in-degree and enqueue when zero
  • Compare processed count to numCourses and return result
207. Course Schedule.cpp

Possibly linked issues

  • 51 solution added #207: The PR adds the C++ solution for LeetCode problem 207, which directly addresses the problem detailed in the issue.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for raising the PR, the owner will be review it soon' keep patience, keep contributing>>>!!! make sure you have star ⭐ the repo

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@SjxSubham SjxSubham added the hacktoberest-accepted hacktoberfest-accepted label Oct 20, 2025
@SjxSubham
Copy link
Owner

@kavishnasta Star the repo as well...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hacktoberest-accepted hacktoberfest-accepted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

207. Course Schedule

2 participants