Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 210 · Topological Sort / DAG

Course Schedule II

LeetCode 210 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

DFS post-order, reversed = topological order.

మధ్యస్థంDepth-First SearchBreadth-First SearchGraph TheoryTopological Sort
LeetCode లో తెరవండి ↗

నేను Course Schedule II (LeetCode 210) ను ఇలా పరిష్కరించాను — Topological Sort / DAG ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

Same cycle detection, but now record each node after all its dependants are finished. Reversing that finishing order gives a valid order to take the courses (a topological sort).

Approach

  1. 1

    DFS with path markers; cycle → [].

  2. 2

    Append each node to the stack when its DFS finishes.

  3. 3

    Return the stack reversed.

నేను ఎలా పరిష్కరించాను

DFS topological sortPythonO(V+E) time
class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        adj = defaultdict(list)
        for v,u in prerequisites:
            adj[u].append(v)
        path_visited = [False]*numCourses
        visited = set()
        stack = []
        
        def dfs(node):
            visited.add(node)
            path_visited[node]=1
            for adj_node in adj[node]:
                if adj_node not in visited:
                    if dfs(adj_node): #has cycle
                        return True
                elif path_visited[adj_node]==1: #already visited in the current path
                    return True
            #before coming back
            stack.append(node)
            path_visited[node]=0
            return False
            
        for node in range(numCourses):
            if node not in visited:
                if dfs(node): #has cycle
                    return []
        return stack[::-1]
స్టెప్-త్రూ లోడ్ అవుతోంది…

Course Schedule II — తరచూ అడిగే ప్రశ్నలు

Course Schedule II వెనుక ఉన్న intuition ఏమిటి?

Same cycle detection, but now record each node after all its dependants are finished. Reversing that finishing order gives a valid order to take the courses (a topological sort).

Course Schedule II (LeetCode 210) ను ఎలా పరిష్కరించాలి?

1. DFS with path markers; cycle → []. 2. Append each node to the stack when its DFS finishes. 3. Return the stack reversed.

Course Schedule II యొక్క time, space complexity ఎంత?

Time: O(V + E). Space: O(V + E). (Accepted approach: DFS topological sort.)

Course Schedule II లో సాధారణ పొరపాట్లు ఏమిటి?

Many orders are valid — any topological order is accepted.