Skip to content

Commit

Permalink
Time: 6 ms (56.08%) | Memory: 46.4 MB (10.49%) - LeetSync
Browse files Browse the repository at this point in the history
  • Loading branch information
Rupa-Rd committed Dec 12, 2024
1 parent 95255ce commit d60f2c8
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions 210-course-schedule-ii/course-schedule-ii.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();

for(int i = 0; i < numCourses; i++){
graph.add(new ArrayList<>());
}

for(int i = 0; i < prerequisites.length; i++){
graph.get(prerequisites[i][1]).add(prerequisites[i][0]);
}

int[] indegree = new int[numCourses];
for(int i = 0; i < numCourses; i++){
for(int neigh: graph.get(i)){
indegree[neigh] ++;
}
}

Queue<Integer> q = new LinkedList<>();

for(int i = 0; i < numCourses; i++){
if(indegree[i] == 0){
q.add(i);
}
}
int[] topo = new int[numCourses];
int i = 0;

while(!q.isEmpty()){
int top = q.poll();
topo[i++] = top;

for(int neigh: graph.get(top)){
indegree[neigh] --;
if(indegree[neigh] == 0){
q.add(neigh);
}
}
}

if(i == numCourses){
return topo;
}else{
return new int[]{};
}
}
}

0 comments on commit d60f2c8

Please sign in to comment.