Start learning free

LESSON 285 OF 314 · GRAPHS

Course Schedule in Go: Topological Sort with Kahn's Algorithm

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

    GO · GRAPHS

    Course Schedule in Go, explained

    Problem overview

    The function canFinish receives numCourses, the number of courses (labelled 0 to numCourses - 1), and prerequisites, a slice of pairs. A pair [a, b] means course b must be taken before course a. The function returns true when some order lets you take every course, and false otherwise.

    With numCourses = 2 and prerequisites = [[1, 0]] the answer is true: take course 0, then course 1. With prerequisites = [[1, 0], [0, 1]] the answer is false, because each course waits for the other and neither can start. With numCourses = 4 and prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]] the answer is true: course 0 needs nothing, courses 1 and 2 need 0, and course 3 needs both 1 and 2, so the order 0, 1, 2, 3 works.

    Approach: take free courses and unlock the rest

    Draw each pair [a, b] as an arrow from b to a, from the course to take first to the course that depends on it. All courses can be finished exactly when there is an order in which every arrow points forward, called a topological order. Such an order exists exactly when the arrows contain no cycle.

    Kahn's algorithm builds that order directly:

    1. Count, for every course, how many prerequisites it still waits for. This count is its in-degree, the number of arrows pointing into it.
    2. Put every course with a count of 0 in a queue. These can be taken right now.
    3. Take a course from the queue. For each course that waits for it, lower that course's count by 1. If a count reaches 0, that course is free: add it to the queue.
    4. Repeat until the queue is empty, and count the courses taken.

    If every course was taken, the answer is true. Courses on a cycle wait for each other, so their counts never reach 0 and they are never taken. The same holds for any course that depends on one of them. If any course is left over, the answer is false.

    Each course enters the queue at most once and each arrow is looked at once, so the work grows with the number of courses plus the number of pairs.

    Step by step

    1. Create graph as a slice of numCourses int slices with make. graph[b] will hold the courses that wait for course b. The inner slices start as nil, and append works on a nil slice, so they need no setup.
    2. Create inDegree, a slice of numCourses ints. make fills it with zeros.
    3. Loop over prerequisites with range, naming each pair prereq.
    4. Record the arrow. Append prereq[0] to graph[prereq[1]], and store the result back, because append returns the grown slice.
    5. Count the prerequisite. Add 1 to inDegree[prereq[0]].
    6. Create the queue as an empty int slice, []int{}. A slice works as a queue: append adds at the back and reslicing removes the front.
    7. Seed the queue. Loop over every course and append the ones whose inDegree is 0.
    8. Start a counter named taken at 0.
    9. Loop while len(queue) > 0. Go's for with only a condition plays the role of while.
    10. Take the front course. Copy queue[0] into course, drop it with queue = queue[1:], and add 1 to taken.
    11. Unlock the dependants. Range over graph[course]. For each nextCourse, subtract 1 from its in-degree, and if that reaches 0, append it to the queue.
    12. Return taken == numCourses.

    The solution in Go

    func canFinish(numCourses int, prerequisites [][]int) bool {
        graph := make([][]int, numCourses)
        inDegree := make([]int, numCourses)
        for _, prereq := range prerequisites {
            graph[prereq[1]] = append(graph[prereq[1]], prereq[0])
            inDegree[prereq[0]]++
        }
        queue := []int{}
        for course := 0; course < numCourses; course++ {
            if inDegree[course] == 0 {
                queue = append(queue, course)
            }
        }
        taken := 0
        for len(queue) > 0 {
            course := queue[0]
            queue = queue[1:]
            taken++
            for _, nextCourse := range graph[course] {
                inDegree[nextCourse]--
                if inDegree[nextCourse] == 0 {
                    queue = append(queue, nextCourse)
                }
            }
        }
        return taken == numCourses
    }
    

    The Go details worth a closer look:

    • append must be assigned. append may allocate a bigger array, so it returns the new slice. Writing append(graph[prereq[1]], prereq[0]) on its own line would discard the result, and Go rejects it with an error that the value is not used.
    • make([][]int, n) gives n nil slices. Reading graph[x] for a course nobody depends on gives an empty slice, and ranging over it does nothing.
    • Reslicing as a dequeue. queue[1:] does not copy anything; it moves the start of the slice forward. Each course is appended once, so the total work stays linear.
    • range with _. range yields an index and a value. A variable you don't use is a compile error in Go, so the index is dropped with _.
    • ++ and -- are statements. inDegree[prereq[0]]++ works on its own line, but it can't be used inside an expression.

    A trace

    For numCourses = 4 and prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]], the graph and in-degrees are built first. Then each line below is printed after a course is taken:

    graph [[1 2] [3] [3] []] inDegree [0 1 1 2]
    took 0 inDegree [0 0 0 2] queue [1 2] taken 1
    took 1 inDegree [0 0 0 1] queue [2] taken 2
    took 2 inDegree [0 0 0 0] queue [3] taken 3
    took 3 inDegree [0 0 0 0] queue [] taken 4
    

    Now a case with a cycle: numCourses = 4 and prerequisites = [[1, 0], [2, 1], [1, 2], [3, 0]]. Courses 1 and 2 need each other.

    graph [[1 3] [2] [1] []] inDegree [0 2 1 1]
    took 0 inDegree [0 1 1 0] queue [3] taken 1
    took 3 inDegree [0 1 1 0] queue [] taken 2
    

    Only 2 of 4 courses are taken. Courses 1 and 2 keep a count of 1 forever, so the function returns false.

    Complexity

    Let V be numCourses and E the number of pairs.

    Time: O(V + E). Building the graph touches each pair once. Seeding the queue checks each course once. Each course is taken at most once, and when it is taken, its list of dependants is walked once, which covers every pair exactly one time over the whole run.

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

    Edge cases and common mistakes

    • No prerequisites. Every in-degree is 0, every course goes in the queue, and the result is true. This works for nil as well as an empty slice.
    • A single course. numCourses = 1 with no pairs returns true.
    • Cycles of any length. The two-course cycle is the smallest, but a cycle through three courses, [[0, 1], [1, 2], [2, 0]], returns false too: no course starts with a count of 0, so the queue starts empty.
    • A cycle in one part of the graph. Other courses can still be taken, but the final comparison with numCourses fails. Checking only that the queue starts non-empty is not enough.
    • Reversing the arrow. In [a, b] the course to take first is b. Adding b to graph[a] and counting b's in-degree would answer for the reverse graph. That happens to give the same true or false answer, but the order in which courses are taken would be wrong, so keep the arrow direction as the statement gives it.
    • Forgetting to store append's result. The queue or the graph stays unchanged, and the code either fails to compile or gives wrong answers.
    • Queueing a course twice. A course is queued only when its count reaches exactly 0, and a count reaches 0 only once, so no check for duplicates is needed.

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