MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / prerequisites

Function prerequisites

python3/Graphs/prerequisites.py:5–30  ·  view source on GitHub ↗
(n: int, prerequisites: List[List[int]])

Source from the content-addressed store, hash-verified

3
4
5def prerequisites(n: int, prerequisites: List[List[int]]) -> bool:
6 graph = defaultdict(list)
7 in_degrees = [0] * n
8 # Represent the graph as an adjacency list and record the in-
9 # degree of each course.
10 for prerequisite, course in prerequisites:
11 graph[prerequisite].append(course)
12 in_degrees[course] += 1
13 queue = deque()
14 # Add all courses with an in-degree of 0 to the queue.
15 for i in range(n):
16 if in_degrees[i] == 0:
17 queue.append(i)
18 enrolled_courses = 0
19 # Perform topological sort.
20 while queue:
21 node = queue.popleft()
22 enrolled_courses += 1
23 for neighbor in graph[node]:
24 in_degrees[neighbor] -= 1
25 # If the in-degree of a neighboring course becomes 0, add
26 # it to the queue.
27 if in_degrees[neighbor] == 0:
28 queue.append(neighbor)
29 # Return true if we've successfully enrolled in all courses.
30 return enrolled_courses == n

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected