Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 207 · Topological Sort / DAG

Course Schedule

LeetCode 207 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Cycle detection with path-visited markers.

நடுத்தரம்Depth-First SearchBreadth-First SearchGraph TheoryTopological SortDirected Acyclic Graph
LeetCode இல் திற ↗

நான் Course Schedule (LeetCode 207) ஐ இப்படித் தீர்த்தேன் — Topological Sort / DAG பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Courses are nodes and prerequisites are directed edges. You can finish everything exactly when there's no cycle. DFS with a 'currently on the path' marker finds a cycle as soon as you meet a node that is still on the path.

Approach

  1. 1

    Build edges prerequisite → course.

  2. 2

    DFS marks a node visited and on-path.

  3. 3

    Meeting an on-path node means a cycle.

  4. 4

    Unmark on the way back.

நான் எப்படித் தீர்த்தேன்

DFS cycle detectionPythonO(V+E) time
class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        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 False
        return len(stack)==numCourses
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Course Schedule — அடிக்கடி கேட்கப்படும் கேள்விகள்

Course Schedule பின்னாலுள்ள intuition என்ன?

Courses are nodes and prerequisites are directed edges. You can finish everything exactly when there's no cycle. DFS with a 'currently on the path' marker finds a cycle as soon as you meet a node that is still on the path.

Course Schedule (LeetCode 207) ஐ எப்படித் தீர்ப்பது?

1. Build edges prerequisite → course. 2. DFS marks a node visited and on-path. 3. Meeting an on-path node means a cycle. 4. Unmark on the way back.

Course Schedule இன் time மற்றும் space complexity என்ன?

Time: O(V + E). Space: O(V + E). (Accepted approach: DFS cycle detection.)

Course Schedule இல் பொதுவான தவறுகள் என்ன?

visited alone isn't enough — a node finished in another branch isn't a cycle.