← Google bank

Google · Question 66 · Graphs

Course Schedule II

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

Problem

Return an order of courses you should take to finish all courses (topological sort).

Approach

Use BFS (Kahn's algorithm) to perform topological sorting.

Time O(V+E)Space O(V+E)

How it works

  1. 1Build the graph and indegree array.
  2. 2Enqueue all courses with no prerequisites.
  3. 3Remove edges and enqueue newly freed courses.
  4. 4Return the order if all courses are included.

Sample input / output

Input:
2 1
1 0
Output:
[0, 1]

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 3Branches 2Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeatyes↻ repeat↻ repeatyesnoSTARTfrom collections importdequeDEFINEfindOrder(numCourses,prerequisites)graph = [[] for _ inrange(numCourses)]indegree = [0] * numCoursesfor u, v inprerequisitesgraph[v].append(u)indegree[u] += 1queue = deque([i for i inrange(numCourses) ifindegree[i] == 0])order = []while queuenode = queue.popleft()order.append(node)for neighbor ingraph[node]indegree[neighbor] -= 1if indegree[neighbor]== 0queue.append(neighbor)RETURN order if len(order)== numCourses else []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(findOrder(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