Home › Company-wise questions › Meta (Facebook) › Course Schedule (Cycle Detection) ← Meta (Facebook) bank
Meta (Facebook) · Question 60 · Graphs
Course Schedule (Cycle Detection) Graphs Python code ⏱ O(v+e) 💾 O(v+e)
Product-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
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 Build the graph with indegree counts. 2 Drain prerequisite-free courses first. 3 Unprocessed 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 Flowchart Pseudocode
Time O(v+e)Space O(v+e)Loops 4Branches 3Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
↻ repeat yes ↻ repeat ↻ repeat ↻ repeat yes ↻ repeat ↻ repeat yes no START from collections import deque DEFINE canFinish(numCourses, prerequisites) graph = [[] for _ in range(numCourses)] indegree = [0] * numCourses for pre in prerequisites graph[pre[1]].append(pre[0]) indegree[pre[0]] += 1 q = deque() for i in range(numCourses) if indegree[i] == 0 q.append(i) count = 0 while q course = q.popleft() count += 1 for next_course in graph[course] indegree[next_course] -= 1 if indegree[next_course] == 0 q.append(next_course) RETURN count == numCourses DEFINE main() import sys data = 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← Q59 · Clone Graph Q61 · Pacific Atlantic Water Flow → Solution code Core logic highlighted in green
Language Pythonsource Java C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →