Short and Simple


  • 7

    Took 99ms.

    class Solution:
        def findOrder(self, numCourses, prerequisites):
            from collections import *
            pre, suc = defaultdict(int), defaultdict(list)
            for a, b in prerequisites:
                pre[a] += 1
                suc[b].append(a)
            free = set(range(numCourses)) - set(pre)
            out = []
            while free:
                a = free.pop()
                out.append(a)
                for b in suc[a]:
                    pre[b] -= 1
                    pre[b] or free.add(b)
            return out * (len(out) == numCourses)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.