Google · Question 65 · Graphs
Course Schedule
Problem
Given prerequisites, check if you can finish all courses (detect cycle in directed graph).
Approach
Use DFS to detect cycles.
Time O(V+E)Space O(V+E)
How it works
- 1Build the adjacency list from prerequisites.
- 2Use DFS with states: 0=unvisited, 1=visiting, 2=visited.
- 3A back edge (cycle) appears if a node is visited twice in the stack.
- 4Return False if a cycle is found.
Sample input / output
Input: 2 2 1 0 0 1 Output: False
Constraints
1 <= numCourses <= 2000; 0 <= prerequisites.length <= 5000; all pairs unique.
Solution — read it, then walk it
Time O(V+E)Space O(V+E)Loops 2Branches 4Returns 5source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/27
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits