Leetcode 1101 Solution

This article provides solution to leetcode question 1101 (parallel-courses)

https://leetcode.com/problems/parallel-courses

Solution

class Solution:
    def minimumSemesters(self, n: int, relations: List[List[int]]) -> int:
        nodes = set(list(range(1, n + 1)))

        child_nodes = collections.defaultdict(set)
        parent_nodes = collections.defaultdict(set)
        for src, dst in relations:
            child_nodes[src].add(dst)
            parent_nodes[dst].add(src)

        q = collections.deque()
        for node in nodes:
            if len(parent_nodes[node]) == 0:
                q.append(node)

        ans = 0
        while q:
            s = len(q)

            for _ in range(s):
                node = q.popleft()
                nodes.remove(node)

                for child_node in child_nodes[node]:
                    if child_node not in nodes:
                        continue

                    parent_nodes[child_node].remove(node)

                    if len(parent_nodes[child_node]) == 0:
                        q.append(child_node)

            ans += 1

        return ans if len(nodes) == 0 else -1