← Meta (Facebook) bank

Meta (Facebook) · Question 60 · Graphs

Course Schedule (Cycle Detection)

GraphsPythoncode⏱ O(v+e)💾 O(v+e)
Product-based

Problem

You are given number of courses and prerequisites. Check if you can finish all courses.

Approach

Kahn's BFS: emit zero-indegree courses; leftovers mean a cycle.

Time O(v+e)Space O(v+e)

How it works

  1. 1Build the graph with indegree counts.
  2. 2Drain prerequisite-free courses first.
  3. 3Unprocessed courses sit in a cycle.

Sample input / output

Input:
2 2
1 0
0 1
Output:
False

Constraints

1 <= numCourses <= 2000; 0 <= prerequisites.length <= 5000.

Solution — read it, then walk it

Time O(v+e)Space O(v+e)Loops 4Branches 3Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyes↻ repeat↻ repeat↻ repeatyes↻ repeat↻ repeatyesnoSTARTfrom collections importdequeDEFINEcanFinish(numCourses,prerequisites)graph = [[] for _ inrange(numCourses)]indegree = [0] * numCoursesfor pre inprerequisitesgraph[pre[1]].append(pre[0])indegree[pre[0]] += 1q = deque()for i inrange(numCourses)if indegree[i] == 0q.append(i)count = 0while qcourse = q.popleft()count += 1for next_course ingraph[course]indegree[next_course] -= 1ifindegree[next_course]== 0q.append(next_course)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/30

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