← Google bank

Google · Question 65 · Graphs

Course Schedule

GraphsPythoncode⏱ O(V+E)💾 O(V+E)
Product-based

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

  1. 1Build the adjacency list from prerequisites.
  2. 2Use DFS with states: 0=unvisited, 1=visiting, 2=visited.
  3. 3A back edge (cycle) appears if a node is visited twice in the stack.
  4. 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.
↻ repeatyesnoyesnoyes↻ repeatyesnoSTARTnumCourses, prerequisitesgraph = [[] for _ inrange(numCourses)]for u, v inprerequisitesgraph[v].append(u)visited = [0] * numCoursesDEFINE dfs(i)if visited[i] == 1RETURN Falseif visited[i] == 2RETURN Truevisited[i] = 1for neighbor ingraph[i]if not dfs(neighbor)RETURN Falsevisited[i] = 2RETURN TrueRETURN all(dfs(i) for i inrange(numCourses))DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)numCourses = int(next(it));e = int(next(it))prerequisites =[[int(next(it)),int(next(it))] for _ i…print(canFinish(numCourses,prerequisites))if __name__ =="__main__"main()END
  • 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