Start learning free

LESSON 285 OF 314 · GRAPHS

Course Schedule in Swift: Kahn's Algorithm in O(V + E)

Practice O(V + E) Read the full explanation

You get numCourses courses, numbered 0 to numCourses - 1. You also get an array prerequisites of pairs [a, b]. A pair means you must finish course b before you start course a.

Return true if you can take all the courses in some order. If you can't, return false.

 

Example 1:

Input: numCourses = 5, prerequisites = [[1, 0], [2, 1], [4, 3], [4, 2]]
Output: true
Explanation: Each arrow goes from a course to a course that needs it:
    0 → 1 → 2 → 4
            3 → 4
Course 4 needs both 2 and 3.
Taking the courses in number order, from 0 to 4, works.

Example 2:

Input: numCourses = 4, prerequisites = [[1, 0], [2, 1], [3, 2], [1, 3]]
Output: false
Explanation: The arrows 1 → 2 → 3 → 1 form a loop.
Course 1 waits for course 3.
Course 3 waits for course 2.
Course 2 waits for course 1.
Course 0 is fine, but the other three can never start.

Example 3:

Input: numCourses = 3, prerequisites = []
Output: true
Explanation: No course has a prerequisite, so any order works.

 

Constraints:

  • 1 to 100,000 courses.
  • Up to 100,000 pairs.
  • Both courses in a pair are valid course numbers.
  • The two courses in a pair are different.
  • No pair appears twice.
STEP 1 OF 16
    Ctrl + Enter to check

    SWIFT · GRAPHS

    Course Schedule in Swift, explained

    Problem overview

    The method canFinish(_ numCourses: Int, _ prerequisites: [[Int]]) -> Bool receives the number of courses, labeled 0 to numCourses - 1, and a list of pairs. A pair [a, b] means course b must be taken before course a. It returns true if all the courses can be finished.

    With numCourses = 2 and prerequisites = [[1, 0]] the answer is true: take course 0, then course 1. With [[1, 0], [0, 1]] the answer is false, because each course waits for the other and neither can start.

    Drawing each pair [a, b] as an arrow from b to a, the courses can all be finished exactly when the arrows contain no cycle. In that case an order exists in which every arrow points forward, called a topological order.

    Approach: keep taking courses that are free

    A course is free when none of its prerequisites is left untaken. Start with the courses that need nothing. Taking one removes its arrows, which may free other courses. Repeat until no free course remains, and count how many were taken. If the count equals numCourses, every course was reachable in some valid order. Otherwise the leftover courses are on a cycle, or wait for one, and the answer is false.

    This is Kahn's algorithm. To do it fast, two things are stored:

    • graph[b] lists the courses that wait for course b.
    • inDegree[a] counts how many prerequisites of course a are still untaken.

    A course is free when its count is 0. Every pair is looked at once while building the data and once while taking courses, so the work is O(V + E) for V courses and E pairs. A depth-first search that looks for cycles is another way to solve the problem, but this lesson uses the counting approach.

    Step by step

    1. Create graph with [[Int]](repeating: [], count: numCourses): one empty list per course.
    2. Create inDegree as numCourses zeros.
    3. Loop over the pairs. For each prereq, prereq[1] comes first and prereq[0] waits for it.
    4. Record the arrow: append prereq[0] to graph[prereq[1]].
    5. Count the prerequisite: inDegree[prereq[0]] += 1.
    6. Create queue as an empty [Int]() that will hold the free courses.
    7. Seed the queue. Loop over every course and append those with inDegree[course] == 0. These are the valid starting points.
    8. Create taken, starting at 0. It counts the courses taken and is also the position in queue of the next one to take.
    9. Loop while taken < queue.count. The queue grows during the loop as courses become free.
    10. Read the next course with queue[taken] and add 1 to taken.
    11. Visit the courses waiting for it: loop over graph[course].
    12. Remove one prerequisite from each with inDegree[nextCourse] -= 1.
    13. If its count reaches 0, append it to the queue. A count reaches 0 only once, so each course joins the queue at most once.
    14. Return taken == numCourses.

    The solution in Swift

    class Solution {
        func canFinish(_ numCourses: Int, _ prerequisites: [[Int]]) -> Bool {
            var graph = [[Int]](repeating: [], count: numCourses)
            var inDegree = [Int](repeating: 0, count: numCourses)
            for prereq in prerequisites {
                graph[prereq[1]].append(prereq[0])
                inDegree[prereq[0]] += 1
            }
            var queue = [Int]()
            for course in 0..<numCourses {
                if inDegree[course] == 0 {
                    queue.append(course)
                }
            }
            var taken = 0
            while taken < queue.count {
                let course = queue[taken]
                taken += 1
                for nextCourse in graph[course] {
                    inDegree[nextCourse] -= 1
                    if inDegree[nextCourse] == 0 {
                        queue.append(nextCourse)
                    }
                }
            }
            return taken == numCourses
        }
    }
    

    The Swift details worth a closer look:

    • Arrays are values. [[Int]](repeating: [], count: numCourses) fills the outer array with copies of the empty array. Each course gets its own inner array, and appending to graph[2] doesn't touch graph[3].
    • The queue is an array read by index. removeFirst() shifts every remaining element, which is slow for a long queue. The code never removes anything: taken marks the front, and the entries before it are courses already taken.
    • The loop condition is re-checked each turn. queue.count changes inside the loop, and the while sees the new value.
    • No ++. Swift has no increment operator, so the code uses += 1 and -= 1.
    • let for course. It never changes after it is read, so let says so.

    Tracing two inputs

    For numCourses = 4 and prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]], the setup gives:

    graph=[[1, 2], [3], [3], []] inDegree=[0, 1, 1, 2]
    queue=[0, 1, 2, 3] taken=4
    

    Only course 0 starts free. Taking it frees courses 1 and 2. Taking those frees course 3. All four are taken, so the result is true.

    Now add a cycle: numCourses = 4 and prerequisites = [[1, 0], [2, 1], [1, 2], [3, 0]]. Courses 1 and 2 wait for each other:

    graph=[[1, 3], [2], [1], []] inDegree=[0, 2, 1, 1]
    queue=[0, 3] taken=2
    

    Course 0 is taken and frees course 3, but course 1 still waits for course 2 and vice versa. Only 2 courses are taken, so the result is false.

    Complexity

    Time: O(V + E). Building graph and inDegree touches each pair once. Seeding the queue looks at each course once. Each course enters the queue at most once, and its list is scanned once, so the main loop looks at each pair once.

    Space: O(V + E). graph holds one entry per pair, and inDegree and queue hold at most one entry per course.

    Edge cases and common mistakes

    • No prerequisites. Every course starts free, so canFinish(3, []) returns true.
    • Reversed arrows. In [a, b], b comes first. Storing the arrow the other way round counts the wrong thing, although some inputs still give the right answer by accident.
    • A cycle away from the start. Course 0 may be free while a different group of courses loops. The answer is false, which is why the result compares taken with numCourses instead of checking that the queue started non-empty.
    • Courses that depend on a cycle. A course that needs a cyclic course never reaches count 0 either, so it is never taken.
    • Using removeFirst() on a big queue. It still gives correct answers, but each call moves the remaining elements, which can make a long run slow.
    • Long chains. There is no recursion, so a chain of 100,000 courses, each needing the one before it, returns true without stack problems.

    Testing

    • numCourses = 2, prerequisites = [[1, 0]] gives true.
    • numCourses = 2, prerequisites = [[1, 0], [0, 1]] gives false.
    • numCourses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]] gives true.
    • numCourses = 3, prerequisites = [] gives true.
    • numCourses = 4, prerequisites = [[1, 0], [2, 1], [1, 2], [3, 0]] gives false.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free