Data Structures & Algorithms Advanced Graphs
💡
Exercise 117

Course Schedule 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Given numCourses and prerequisites [a,b] meaning 'must take b before a', determine if you can finish all courses. This is cycle detection in a directed graph.

numCourses = 4 prereqs = [[1,0],[2,0],[3,1],[3,2]] # 0 -> 1 -> 3 # 0 -> 2 -> 3 # No cycle, can finish = True

Use DFS with 3 states: unvisited, in-progress (currently in DFS path), visited (done). If we revisit an in-progress node, there's a cycle.

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Return True if all courses can be finished, False if there's a cycle.
DFS with states: 0=unvisited, 1=in-progress, 2=done. If you hit a node in state 1, it's a cycle.
🧪 Test Cases
Input
canFinish(4, [[1,0],[2,0],[3,1],[3,2]])
Expected
True
Boolean check
Input
canFinish(2, [[1,0],[0,1]])
Expected
False
Boolean check
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.