← Uber bank

Uber · Question 37 · Graphs

Course Schedule

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

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

  1. 1Build the graph and indegree counts.
  2. 2Process zero-indegree courses BFS-style (Kahn).
  3. 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.
↻ repeat↻ repeatyes↻ repeat↻ repeatyesnoSTARTfrom collections importdequeDEFINEcanFinish(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])count = 0while qnode = q.popleft()count += 1for nei in adj[node]indegree[nei] -= 1if indegree[nei] == 0q.append(nei)RETURN count == numCoursesDEFINE 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