Skip to content

Files

Latest commit

author
DennyZhang
Oct 3, 2019
1a3246a · Oct 3, 2019

History

History
This branch is 1 commit ahead of, 45 commits behind dennyzhang/code.dennyzhang.com:master.

review-topologicalsort

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Oct 3, 2019

Review: Topological Sort Problems


Topological Sort Problems


Basic Abstractions

NameSummary
unexamined nodes with no incoming edges
Unused edge
Wikipedia: Topological sortingKahn’s algorithm, DFS algorithm

Questions

NameExample
Time complexity should be O(n+e)O(n^2) would work, but not optimal
Indegrees as a list of 0s might troublesomeUse hashmap instead Leetcode: Sequence Reconstruction
Common Mistake: Missing characters without incoming edgesLeetcode: Alien Dictionary
Common Mistake: Avoid updating indegrees repetitively for duplicate edgesLeetcode: Alien Dictionary
Common Mistake: in dfs implementation, process 0-degree nodes multiple timesLeetcode: Alien Dictionary
Topoloical sort: How to return all possible orders, instead of any one?
Longest path in a DAG without circleLeetcode: Longest Increasing Path in a Matrix

Code Skeleton

  • Solution: Kahn’s algorithm (BFS) without deleting edges
// https://code.dennyzhang.com/course-schedule
// Basic Ideas: topological sort + Kahn's algorithm
//
//  BFS
//    queue: unexamined nodes with no incoming edges
//    Decrease count of incoming edges for the target nodes
//    Get the next nodes to be examined
//
//  When to stop?
//    When BFS stops, there should be no unexamined edges
//    Or all nodes get examined
//
//  Follow-up: what if there are duplicate edges?
//
// Complexity: Time O(n+e), Space O(n+e)
func canFinish(numCourses int, prerequisites [][]int) bool {
    indegrees := make([]int, numCourses)
    edges := map[int]map[int]bool{}
    for _, p := range prerequisites {
        n1, n2 := p[0], p[1]
        if _, ok := edges[n1]; !ok {
            edges[n1] = map[int]bool{}
        }
        edges[n1][n2] = true
        indegrees[n2]++
    }
    count := 0
    queue := []int{}
    for i, v := range indegrees {
        if v == 0 {
            queue = append(queue, i)
            count++
        }
    }
    for len(queue) > 0 {
        l := []int{}
        for _, n1 := range queue {
            for n2, _ := range edges[n1] {
                indegrees[n2]--
                if indegrees[n2] == 0 {
                    l = append(l, n2)
                    count++
                }
            }
        }
        queue = l
    }
    return count == numCourses
}

Topological sorting forms the basis of linear-time algorithms for finding the critical path of the project, a sequence of milestones and tasks that controls the length of the overall project schedule.

See all topologicalsort problems: #topologicalsort [display-posts tag=”topologicalsort” posts_per_page=”100” orderby=”title”]

See more blog_posts.

linkedin
github
slack