Course Schedule
Given numCourses and a list of prerequisite pairs [a, b] meaning course b must be taken before a, return whether all courses can be finished.
Intuition
The first job is recognising this as a graph problem at all. Draw an edge b -> a for each pair [a, b] and the question becomes structural: you can finish everything exactly when the graph has no cycle, because a cycle is a set of courses each waiting on another with no valid starting point. Kahn's algorithm answers this without a separate cycle check — repeatedly take any course with no unmet prerequisites, and if the process stalls before all courses are taken, the leftovers are the cycle.
Approach
Build the graph and get the edge direction right
The pair [a, b] means 'to take a, first take b'. So the dependency flows b -> a: finishing b unlocks a. Reversing this is the most common error and produces a graph whose cycles happen to coincide, so it passes some tests while being conceptually backwards. Alongside the adjacency list, count the in-degree of each course: how many prerequisites it still has unmet.
Start from courses with no prerequisites
A course is takeable exactly when its in-degree is zero. Seed a queue with every such course. If no course has in-degree zero at the start, every course waits on another and the answer is immediately false — that stall is already the cycle showing itself.
Peel off takeable courses and watch for a stall
Pop a course, mark it taken, and decrement the in-degree of everything it unlocks. Any course whose count reaches zero joins the queue. Continue until the queue empties, then compare the number taken against numCourses. Equal means every course was reachable and no cycle exists. Fewer means the remainder are locked in a cycle where each waits on another and no in-degree ever falls to zero. O(V + E) — each edge is decremented exactly once, and no explicit cycle detection is written anywhere.
Solution & live demo
Edge cases
Every course starts at in-degree 0, all are queued immediately, and the answer is true.
Course 1 has in-degree 1 that nothing can decrement, so it never becomes takeable and the count falls short — correctly false.
Kahn's seeds from every in-degree-0 vertex, so independent groups are processed in parallel with no special handling.
Each duplicate raises the in-degree and is decremented once, so the counts stay balanced and the result is unaffected.