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

मैंने 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.