Limited Time Offer:Up to 20% off Hello Interview Premium
Up to 20% off Hello Interview Premium 🎉
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Overview
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Overview
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing

Tutor

Graphs

Course Schedule

medium

max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
DESCRIPTION (inspired by Leetcode.com)

You have to take a total of numCourses courses, which are labeled from 0 to numCourses - 1. You are given a list of prerequisites pairs, where prerequisites[i] = [a, b] indicates that you must complete course b before course a.

Given the total number of courses and a list of prerequisite pairs, write a function to determine if it is possible to finish all courses.

Example 1:

Input:

numCourses = 3
prerequisites = [[1, 0], [2, 1]]

Output: true

Explanation: You can take courses in the following order: 0, 1, 2.

Example 2:

Input:

numCourses = 3
prerequisites = [[1, 0], [0, 1],[1,2]]

Output: false

Explanation: It is impossible to finish all courses, as you must finish course 1 before course 0 and course 0 before course 1.

Explanation

We can use the following approach to solve this problem:
  1. Start with a course that has no prerequisites.
  2. If that course is a prerequisite for another course, remove it from the prerequisites list.
  3. Now, Find the next course that has no prerequisites, and repeat the process.
When we can't find any more courses with no prerequisites, there are two possibilities:
  • If we have already taken all the courses, then we can return true.
  • Otherwise, we return false (as this means there was a circular dependency in the prerequisites).

Here's a visual representation of the above approach for the input numCourses = 4 and prerequisites = [[1,0],[2,1],[3,1],[2,3]]:
We've represented the input as a graph, where each node represents a course, and the edges represent the prerequisites between the courses.
3210
Start with Node 0
321
Remove Node 0 from the graph, and move to Node 1.
32
Remove Node 1 from the graph, and move to Node 3.
2
Remove Node 3 from the graph and move to Node 2.
At this point, there are no more courses without prerequisites, and we've visited all the courses. So, we can return true.

Cycle

Let's instead consider the input numCourses = 5 and prerequisites = [[1,0],[2,1],[3,2],[4,3],[1,4]]:
We start with Node 0, like before:
43210
Start with Node 0
But now, when we remove Node 0, we can't find any more courses without prerequisites!
4321
Remove Node 0. No nodes to choose from!
At this point, we've only processed 1 course, but there are still 4 courses left. So, we return false.

Topological Sort

The above approach is an application of Topological Sort. If we start by calculating the in-degree of each node, we can find the nodes with an in-degree of 0 and add them to a queue.
Next, while the queue is not empty, we remove a node from the queue. After removing a node, we decrement the in-degree of its neighbors. If any of the neighbors have an in-degree of 0, we add them to the queue.
Each time we remove a node from the queue, we increment a counter. When the queue is finally empty, we check if the counter is equal to the number of courses. If it is, we return true. Otherwise, we return false.
Solution
Python
Language
from collections import defaultdict, deque
class Solution:
def canFinish(self, numCourses, prerequisites):
graph = defaultdict(list)
in_degree = [0] * numCourses
for dest, src in prerequisites:
graph[src].append(dest)
in_degree[dest] += 1
queue = deque([i for i in range(numCourses) if in_degree[i] == 0])
count = 0
while queue:
course = queue.popleft()
count += 1
for neighbor in graph[course]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
return count == numCourses
Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(V + E) where V is the number of courses and E is the number of prerequisites. We visit each node and edge once.

Space Complexity: O(V + E) where V is the number of courses and E is the number of prerequisites. We store the graph as an adjacency list and the in-degree of each node.

Mark as read

Next: Course Schedule II

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

Explanation

Topological Sort

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103


© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress