Course Schedule
LeetCode 207 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Cycle detection with path-visited markers.
मैंने 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
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.
मैंने कैसे हल किया
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)==numCoursesCourse 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.