-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcourse-schedule-ii.py
More file actions
30 lines (24 loc) · 853 Bytes
/
course-schedule-ii.py
File metadata and controls
30 lines (24 loc) · 853 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from collections import defaultdict
from typing import List
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
indeg = [0]*numCourses
adj_list = defaultdict(set)
for child, parent in prerequisites:
adj_list[parent].add(child)
indeg[child] += 1
res = []
stack = []
for i, el in enumerate(indeg):
if el == 0:
stack.append(i)
res.append(i)
while stack:
node = stack.pop()
for nei in adj_list[node]:
indeg[nei] -= 1
if indeg[nei] == 0:
stack.append(nei)
res.append(nei)
if len(res) == numCourses: return res
else: return []