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.