Uber · Question 37 · Graphs
Course Schedule
Problem
Given numCourses and prerequisites pairs [a, b] meaning to take course a you must first take course b, determine if you can finish all courses.
Approach
Detect cycle in directed graph using either Kahn’s algorithm (BFS/topological sort) or DFS with color marking. BFS (Kahn’s): Use indegree array; enqueue no des with indegree 0; process nodes and reduce indegrees; if all nodes processed, no cycle. DFS: Mark nodes as unvisited, visiting, visited; detect back edges. from collections import deque
Time O(V+E)Space O(V+E)
How it works
- 1Build the graph and indegree counts.
- 2Process zero-indegree courses BFS-style (Kahn).
- 3All courses processed means no cycle.
Sample input / output
Input: 2 1 1 0 Output: True
Constraints
1 <= numCourses <= 2000; 0 <= prerequisites.length <= 5000.
Solution — read it, then walk it
Time O(V+E)Space O(V+E)Loops 3Branches 2Returns 1source · 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