Topological Sort Algorithm Interview Questions
Master the Topological Sort algorithm for your coding interviews. Our AI-powered guide provides expert insights, practice problems, and personalized feedback to help you succeed.
Course Schedule
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. Return true if you can finish all courses. Otherwise, return false.
for (const [course, prereq] of prerequisites) { adjList[prereq].push(course); inDegree[course]++; }
const queue = []; for (let i = 0; i < numCourses; i++) { if (inDegree[i] === 0) { queue.push(i); } }
let count = 0; while (queue.length) { const course = queue.shift(); count++; for (const nextCourse of adjList[course]) { inDegree[nextCourse]--; if (inDegree[nextCourse] === 0) { queue.push(nextCourse); } } }
return count === numCourses; } }
This problem is a classic application of topological sort. We can use Kahn's algorithm (using a queue and in-degrees) to solve it. First, build an adjacency list and an in-degree array. Then, add all nodes with an in-degree of 0 to a queue. While the queue is not empty, dequeue a node, increment a counter, and decrement the in-degree of its neighbors. If a neighbor's in-degree becomes 0, enqueue it. Finally, if the counter equals the number of courses, it's possible to finish them all.
Related Algorithm Guides
Explore more algorithm interview guides powered by AI coaching