Course Schedule II
LeetCode 210 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
DFS post-order, reversed = topological order.
நான் 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
DFS with path markers; cycle → [].
- 2
Append each node to the stack when its DFS finishes.
- 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.