64 ms beats 100% of python submissions


  • 1
    B
    class Solution(object):
        def findOrder(self, numCourses, prerequisites):
            """
            :type numCourses: int
            :type prerequisites: List[List[int]]
            :rtype: List[int]
            """
            
            adj_list = {x:[] for x in range(numCourses)}
            isVisited = [0]*numCourses
            stack = []
            retVal = []
            
            if len(prerequisites) == 0:
                retVal.extend(range(0,numCourses))
                return retVal
            
            for x,y in prerequisites:
                adj_list[x].append(y)
                
            for node in adj_list:
                if isVisited[node] != 0: continue
                stack.append(node)
                while(stack):
                    currnode = stack[-1]
                    if isVisited[currnode] == 0:
                        isVisited[currnode] = 1
                    elif isVisited[currnode] == 1:
                        j = stack.pop()
                        retVal.append(j)
                        isVisited[currnode] = 2
                        continue
                    elif isVisited[currnode] == 2:
                        stack.pop()
                        continue
                    for x in adj_list[currnode]:
                        if isVisited[x] == 1:
                            return []
                        stack.append(x)
            return retVal

Log in to reply
 

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