Solving Leetcode Interviews in Seconds with AI: Course Schedule II
Introduction
In this blog post, we will explore how to solve the LeetCode problem "210" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array. Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: [0,1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. Example 2: Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] Output: [0,2,1,3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. Example 3: Input: numCourses = 1, prerequisites = [] Output: [0] Constraints: 1 <= numCourses <= 2000 0 <= prerequisites.length <= numCourses * (numCourses - 1) prerequisites[i].length == 2 0 <= ai, bi < numCourses ai != bi All the pairs [ai, bi] are distinct.
Explanation
Here's the solution:
- Topological Sort: The problem is essentially asking for a topological sort of a directed graph where courses are nodes and prerequisites are edges. We use Kahn's algorithm for topological sorting.
- Indegree Calculation: First, calculate the indegree (number of incoming edges) for each course.
Queue-based Processing: Start with courses having indegree 0 and add them to a queue. Then, process the queue: remove a course, add it to the result, and decrement the indegree of its neighbors. If any neighbor's indegree becomes 0, add it to the queue. If at the end, the number of visited courses equals the total number of courses, a topological sort is possible.
Time & Space Complexity: O(V + E), where V is the number of courses and E is the number of prerequisites. Storage Complexity is O(V+E) for the adjacency list and indegree array.
Code
from collections import deque
def findOrder(numCourses, prerequisites):
"""
Finds a possible ordering of courses to take to finish all courses.
Args:
numCourses: The total number of courses.
prerequisites: A list of prerequisite pairs [ai, bi], where ai depends on bi.
Returns:
A list representing a valid course order, or an empty list if it is impossible
to finish all courses.
"""
# Build the adjacency list and indegree array
adj_list = [[] for _ in range(numCourses)]
indegree = [0] * numCourses
for course, pre in prerequisites:
adj_list[pre].append(course)
indegree[course] += 1
# Initialize the queue with courses having indegree 0
queue = deque([i for i in range(numCourses) if indegree[i] == 0])
# Perform topological sort
result = []
visited_count = 0
while queue:
course = queue.popleft()
result.append(course)
visited_count += 1
for neighbor in adj_list[course]:
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
queue.append(neighbor)
# Check if all courses were visited
if visited_count == numCourses:
return result
else:
return []