Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 11

Topological Sort for Dependency and Scheduling Problems

This lesson is built with resources from youtube.com, learnprogramming.in.net and 1 more site.

Introduction

Welcome to our next lesson in the graph algorithms module. In our previous session, we developed a crucial skill: detecting cycles in both directed and undirected graphs using Depth-First Search (DFS). We established that the presence of a "back edge" in a DFS traversal is a definitive sign of a cycle.

This lesson builds directly on that foundation. We'll explore topological sort, an algorithm for creating a linear ordering of vertices in a Directed Acyclic Graph (DAG). For every directed edge from vertex u to v, u must come before v in the ordering. The connection to our last lesson is immediate: a topological sort is only possible if the graph has no directed cycles.

This pattern is fundamental in software engineering and system design. It's the core logic behind:

  • Dependency Resolution: Figuring out the correct order to compile modules in a large software project or install packages with dependencies.
  • Task Scheduling: Executing a series of jobs where some jobs must finish before others can begin.
Software Project Workflow Diagram for Dependency Resolution
This diagram shows a typical project workflow. Tasks like 'Implement Feature 1a' depend on 'Design Feature 1'. A topological sort would give a valid sequence of tasks to complete the project, such as Design -> Implement -> Test -> Deploy.

By the end of this lesson, you will be able to apply topological sort to solve exactly these kinds of dependency resolution and scheduling problems using two primary algorithmic approaches.


What is a Topological Sort?

At its core, a topological sort answers the question: "In what order can I do things?". It applies to any set of items with directed, non-circular dependencies.

Prerequisite Graph for Topological Sort
This graph represents course prerequisites. An edge from 4 to 1 means you must complete course 4 before course 1. A topological sort gives a valid sequence of courses you can take, for example: 4, 2, 1, 3. Notice that `[4, 1, 2, 3]` is also a valid ordering. Topological sorts are often not unique.

Let's watch a video that introduces the concept formally and provides a great real-world analogy.

Topological Sort | Kahn's Algorithm | Graph Theory

This video from WilliamFiset introduces topological sort, explains the types of graphs it applies to (DAGs), and clarifies why cycles make it impossible.

Watch the segment from 00:23 to 05:38. Pay attention to the 'getting dressed' analogy and the formal definition of a topological ordering.

As the video explains, if a graph contains a cycle (e.g., you must put on your shoes before your socks, and your socks before your shoes), no valid ordering exists. This is why cycle detection, which we covered previously, is an implicit first step in any topological sort.

There are two main algorithms for performing a topological sort: Kahn's algorithm (which is BFS-based) and a DFS-based approach. We will explore both.


Algorithm 1: Kahn's Algorithm (BFS-based)

Kahn's algorithm has a very intuitive, iterative logic:

  1. Identify a task that has no prerequisites (an "entry point").
  2. Complete that task and add it to your ordered list.
  3. By completing this task, you may have satisfied a prerequisite for other tasks.
  4. Look for the next task that now has no remaining prerequisites and repeat the process until all tasks are done.

This is implemented by tracking the in-degree of each node—the number of incoming edges.

Let's continue with the same video to see how this is implemented using a queue.

Topological Sort | Kahn's Algorithm | Graph Theory

The next segment of the video explains the intuition behind Kahn's algorithm and then walks through a detailed example.

First, watch from 05:38 to 07:09 to understand the high-level idea. Then, continue from 07:09 to 11:16 for a detailed walkthrough showing how the in-degree array and the queue work together to build the topological order.

Kahn's Algorithm: Summary and Cycle Detection

To summarize the process:

  1. Compute In-degrees: Create an array inDegree of size V (number of vertices). Iterate through all edges (u, v) in the graph and increment inDegree[v].
  2. Initialize Queue: Find all vertices with an in-degree of 0 and add them to a queue. These are the starting points with no dependencies.
  3. Process Queue:
    • While the queue is not empty:
      • Dequeue a vertex u.
      • Add u to your result list (the topological order).
      • For each neighbor v of u:
        • Decrement inDegree[v].
        • If inDegree[v] becomes 0, enqueue v.
  4. Check for Cycles: After the loop finishes, if the number of vertices in your result list is less than the total number of vertices V, the graph must contain a cycle. The algorithm got "stuck" because the cycle prevented any of its constituent nodes' in-degrees from ever reaching zero.

This method of cycle detection is a very elegant property of Kahn's algorithm.


Algorithm 2: DFS-based Topological Sort

An alternative approach uses Depth-First Search. The intuition here is slightly different but powerful. Consider a task u and its dependency v (u -> v). When we perform a DFS, to finish visiting u, we must first recursively visit and finish all its dependencies, including v. This means v will always finish before u.

Therefore, if we run a DFS on the entire graph and record the nodes in the reverse order of their finishing times, we get a valid topological sort.

Lecture 14: Depth-First Search (DFS), Topological Sort

This MIT OpenCourseWare lecture explains the DFS-based approach. It frames the problem as 'job scheduling' and provides a proof of correctness by considering the types of edges in a DFS traversal of a DAG.

Watch from 41:16 to 50:31. The key idea is stated at 45:32: 'run DFS, and output the reverse of the finishing times of vertices'. The proof that follows is excellent for understanding why this works and connects back to our previous lesson's concepts of back edges (which are absent in a DAG).

DFS-based Algorithm: Summary and Cycle Detection

  1. Initialize: Create a visited set and a list/stack order to store the result.
  2. DFS Helper Function dfs(u):
    • Mark u as visited.
    • For each neighbor v of u:
      • If v is not visited, call dfs(v).
    • After exploring all neighbors, add u to the order list.
  3. Main Loop: Iterate through all vertices in the graph. If a vertex i is not visited, call dfs(i).
  4. Final Result: The list order contains the vertices in reverse finishing order. Reverse this list to get the final topological sort.

Cycle Detection: We can integrate the three-color (WHITE, GREY, BLACK) DFS from our previous lesson. During the traversal, if we encounter a GREY node (a node currently in the recursion stack), we've found a back edge, which means there's a cycle. At this point, we can abort and report that a topological sort is not possible.


Go Implementations and Trade-offs

Now, let's translate these two algorithms into idiomatic Go code. Both are valid and it's good to be comfortable with either, as one might be simpler to implement depending on the specific problem constraints.

Performing Topological Sorting on a Directed Acyclic Graph in Go

This article provides clean Go implementations for both Kahn's algorithm and the DFS-based approach. It's a great reference for seeing how these algorithms are written in practice.

Please review the Go code in the article. Focus on the TopologicalSortDFS and TopologicalSortKahn methods. Note how each one implements its respective logic for traversal and cycle detection.

Analysis of Approaches

As a senior engineer, it's important to understand the trade-offs between these two methods.

Aspect Kahn's Algorithm (BFS-based) DFS-based Algorithm
Intuition Often more intuitive. Directly models "taking courses whose prerequisites are met." Relies on the property of DFS finishing times, which can be less obvious.
Implementation Requires explicitly calculating and updating in-degrees. The main loop is iterative (using a queue). Can be implemented concisely with recursion. Cycle detection logic needs to be added carefully.
Space Complexity for the in-degree array and the queue. for the visited set and the recursion stack depth (which can be in the worst case).
Parallelism The set of nodes with an in-degree of 0 can be processed in parallel. This is a significant advantage in real-world task schedulers. Inherently sequential due to the recursive nature of DFS.
Cycle Path Reports a cycle exists but doesn't easily produce the nodes in the cycle. Can be more easily adapted to return the nodes in the cycle upon detecting a back edge.

For a standard interview, both are perfectly acceptable. However, in a system design context where you might be building a concurrent task execution engine, the insight that Kahn's algorithm naturally exposes parallelism is a valuable point to discuss.


Application: A Concurrent Task Scheduler

Let's briefly look at how topological sort is used in a real-world system. The following article describes a Go library for running tasks with dependencies, a perfect application of our topic.

Using Go To Schedule And Run Tasks with Dependencies

This article discusses deprunlib, a Go library for concurrent task execution. It's a great example of applying topological sort to a practical system design problem.

Read the 'Summary', 'Data Model', 'Topological Sort', and 'Algorithm High-Level View' sections. You don't need to dive into the full library implementation, but focus on how the problem is modeled as a DAG and how topological sort is used to create a scheduling algorithm.

The key takeaway is that the scheduler doesn't just execute the topologically sorted list sequentially. Instead, it uses the dependencies to feed a worker pool. Kahn's algorithm is particularly well-suited for this: the queue of nodes with in-degree 0 represents the set of tasks that are "ready to run" concurrently.


Practice Problem: Course Schedule II

Let's solidify your understanding with a classic interview problem.

Problem: You are given numCourses and a list of prerequisites as pairs [course, prerequisite]. Return one valid order you can take the courses to finish all of them. If it's impossible, return an empty array.

This is LeetCode #210, a direct application of topological sort.

Example:

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

This means:

  • To take course 1, you must finish 0.
  • To take course 2, you must finish 0.
  • To take course 3, you must finish 1.
  • To take course 3, you must finish 2.

A valid output would be [0, 1, 2, 3] or [0, 2, 1, 3].

Your Task:
In your editor, outline how you would solve this using Kahn's algorithm in Go. Think about:

  1. How will you represent the graph?
  2. How will you calculate the initial in-degrees?
  3. What is the main loop logic?
  4. How do you detect if a valid order is impossible (i.e., a cycle exists)?

After you've sketched it out, here is a possible implementation:

Click to see the Go solution using Kahn's Algorithm
func findOrder(numCourses int, prerequisites [][]int) []int {
    // 1. Build adjacency list and in-degree array
    adj := make([][]int, numCourses)
    inDegree := make([]int, numCourses)
    for _, prereq := range prerequisites {
        course := prereq[0]
        dependency := prereq[1]
        adj[dependency] = append(adj[dependency], course)
        inDegree[course]++
    }

    // 2. Initialize queue with courses having in-degree of 0
    queue := []int{}
    for i := 0; i < numCourses; i++ {
        if inDegree[i] == 0 {
            queue = append(queue, i)
        }
    }

    // 3. Process the queue
    topoOrder := []int{}
    for len(queue) > 0 {
        // Dequeue
        course := queue[0]
        queue = queue[1:]
        
        topoOrder = append(topoOrder, course)

        // For each neighbor, decrement in-degree
        for _, neighbor := range adj[course] {
            inDegree[neighbor]--
            if inDegree[neighbor] == 0 {
                queue = append(queue, neighbor)
            }
        }
    }

    // 4. Check for cycle
    if len(topoOrder) == numCourses {
        return topoOrder
    }
    
    // If the number of courses in the order is not equal to total courses,
    // there was a cycle.
    return []int{}
}

Conclusion

In this lesson, we demystified topological sort, a fundamental algorithm for ordering elements with dependencies. We saw its direct relevance to real-world engineering problems like build systems and task schedulers.

Key Takeaways:

  • A topological sort is a linear ordering of vertices in a Directed Acyclic Graph (DAG).
  • The presence of a cycle makes a topological sort impossible.
  • Kahn's Algorithm (BFS-based) iteratively processes nodes with an in-degree of 0. It's intuitive and naturally exposes tasks that can be run in parallel.
  • The DFS-based algorithm produces a topological sort by taking the reverse of the nodes' finishing times. It's a clever application of DFS properties.
  • Both algorithms have a time complexity of , as they must traverse the entire graph.

In our next and final lesson for this module, we will explore another powerful graph technique: the Union-Find data structure, which is exceptionally efficient for solving problems related to connected components and network connectivity.