Course Schedule
Course Schedule
There are numCourses courses labeled 0 to numCourses-1. Some courses have prerequisites: a prerequisite pair [a, b] means you must take course b before course a. Determine if it's possible to finish all courses (i.e., no cyclic dependency). Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: 2 courses, prerequisite [1,0] → YES. 2 courses, prerequisites [1,0] and [0,1] → NO (cycle)
Input format — only if your code reads from stdin
Input format (stdin): - First line: two integers numCourses and numPrerequisites - Next numPrerequisites lines: two integers a b (must take b before a) Output: YES if all courses can be finished (no cycle), NO otherwise.
Approach
Detect a cycle in a directed graph. Build adjacency list, then run DFS with three states per node: 0=unvisited, 1=in-progress (currently in DFS stack), 2=done. If you reach a node with state 1 during DFS, a cycle exists.
Input
Output
- •
1 ≤ numCourses ≤ 2000, 0 ≤ numPrerequisites ≤ 5000
More Graphs problems
Browse all coding problems →Press Run to test your custom input, or Submit to judge against all test cases.
Sign in to continue
Create a free account to run code, submit solutions and track progress.
- Free forever — no credit card
- 10+ languages with live execution
- Points, streaks & leaderboards