← Uber bank

Uber · Question 42 · Graphs

Course Schedule II

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

Problem

Same as Course Schedule but return one possible order to finish all courses or empty list if impossible.

Approach

Use topological sort (Kahn's BFS). Build the order list; empty when a cycle exists.

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

How it works

  1. 1Build the graph and indegrees.
  2. 2Emit zero-indegree courses BFS-style.
  3. 3Full order means feasible; else return [].

Sample input / output

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

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.
↻ repeat↻ repeatyes↻ repeat↻ repeatyesnoSTARTfrom collections importdequeDEFINEfindOrder(numCourses,prerequisites)adj = [[] for _ inrange(numCourses)]indegree = [0] * numCoursesfor a, b inprerequisitesadj[b].append(a)indegree[a] += 1q = deque([i for i inrange(numCourses) ifindegree[i] == 0])order = []while qnode = q.popleft()order.append(node)for nei in adj[node]indegree[nei] -= 1if indegree[nei] == 0q.append(nei)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