← Home

210. Course Schedule II

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
210

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 210. Course Schedule II, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • Approach 2: Using Node Indegree
  • time: O(N), space: O(N)

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are findOrder, incomingEdgeCount, init, dfs.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The queue gives the solution a level-by-level or frontier-style traversal.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N), space: O(N)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Approach 2: Using Node Indegree
02//Runtime: 24 ms, faster than 81.55% of C++ online submissions for Course Schedule II.
03//Memory Usage: 10.9 MB, less than 100.00% of C++ online submissions for Course Schedule II.
04//time: O(N), space: O(N)
05class Solution {
06public:
07    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
08        vector<int> incomingEdgeCount(numCourses, 0);
09        vector<vector<int>> edges(numCourses);
10        
11        for(vector<int>& pre : prerequisites){
12            incomingEdgeCount[pre[0]]++;
13            edges[pre[1]].push_back(pre[0]);
14        }
15        
16        queue<int> qNoIncomingEdges;
17        for(int i = 0; i < numCourses; i++){
18            if(incomingEdgeCount[i] == 0){
19                qNoIncomingEdges.push(i);
20            }
21        }
22        
23        int remainingEdgeCount = prerequisites.size();
24        vector<int> ans;
25        while(!qNoIncomingEdges.empty()){
26            int cur = qNoIncomingEdges.front(); qNoIncomingEdges.pop();
27            ans.push_back(cur);
28            for(int nei : edges[cur]){
29                remainingEdgeCount--;
30                if(--incomingEdgeCount[nei] == 0){
31                    qNoIncomingEdges.push(nei);
32                }
33            }
34        }
35        
36        if(remainingEdgeCount != 0) ans.clear();
37        
38        return ans;
39    }
40};
41
42//Approach 1: Using Depth First Search
43//Runtime: 36 ms, faster than 23.25% of C++ online submissions for Course Schedule II.
44//Memory Usage: 13 MB, less than 100.00% of C++ online submissions for Course Schedule II.
45//time: O(N), space: O(N)
46enum class Color{
47    WHITE, GRAY, BLACK
48};
49
50class Solution {
51public:
52    bool isCyclic;
53    unordered_map<int, Color> color;
54    unordered_map<int, vector<int>> adjList;
55    vector<int> topologicalOrder;
56    
57    void init(int numCourses){
58        this->isCyclic = false;
59        
60        for(int i = 0; i < numCourses; i++){
61            this->color[i]= Color::WHITE;
62        }
63    }
64    
65    void dfs(int node){
66        if(this->isCyclic) return;
67        
68        this->color[node] = Color::GRAY;
69        
70        for(int nei : this->adjList[node]){
71            if(this->color[nei] == Color::WHITE){
72                this->dfs(nei);
73            }else if(this->color[nei] == Color::GRAY){
74                this->isCyclic = true;
75            }
76        }
77        
78        this->color[node] = Color::BLACK;
79        this->topologicalOrder.push_back(node);
80    }
81    
82    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
83        this->init(numCourses);
84        
85        for(vector<int>& pre : prerequisites){
86            adjList[pre[1]].push_back(pre[0]);
87        }
88        
89        for(int i = 0; i < numCourses; i++){
90            if(this->color[i] == Color::WHITE){
91                this->dfs(i);
92            }
93        }
94        
95        vector<int> order;
96        if(!this->isCyclic){
97            order = vector<int>(numCourses, 0);
98            for(int i = 0; i < numCourses; i++){
99                order[i] = this->topologicalOrder[numCourses-i-1];
100            }
101        }
102        
103        return order;
104    }
105};

Cost

Complexity

Time
O(N), space: O(N)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.