Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Find Eventual Safe States

Posted on March 25, 2018July 26, 2020 by braindenny

Find Eventual Safe States



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #graph, #topologicalsort, #colorgraph

In a directed graph, we start at some node and every turn, walk along a directed edge of the graph. If we reach a node that is terminal (that is, it has no outgoing directed edges), we stop.

Now, say our starting node is eventually safe if and only if we must eventually walk to a terminal node. More specifically, there exists a natural number K so that for any choice of where to walk, we must have stopped at a terminal node in less than K steps.

Which nodes are eventually safe? Return them as an array in sorted order.

The directed graph has N nodes with labels 0, 1, …, N-1, where N is the length of graph. The graph is given in the following form: graph[i] is a list of labels j such that (i, j) is a directed edge of the graph.

Example:

Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]

Here is a diagram of the above graph.

Leetcode: Find Eventual Safe States

Note:

graph will have length at most 10000.
The number of edges in the graph will not exceed 32000.
Each graph[i] will be a sorted list of different integers, chosen within the range [0, graph.length – 1].

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Solution: DFS + colorgraph
// Basic Ideas: dfs + postorder
//
// Key observation: if one node is unsafe, the nodes point to it will be unsafe too
//
// Coloring nodes with 4 state: unknown, visiting, unsafe, safe
//  Visiting is an intermidate state, which results in either unsafe or safe
//
// Complexity: Time O(n+w), Space O(n+w)
const (
    Unknown = iota
    Visiting = iota
    Unsafe = iota
    Safe = iota
)

func dfs(i int, states []int, graph [][] int) {
    if states[i] != Unknown {
        if states[i] == Visiting {
            states[i] = Unsafe
        }
        return
    }
    states[i] = Visiting
    for _, j := range graph[i] {
        dfs(j, states, graph)
        if states[j] == Unsafe {
            states[i] = Unsafe
            return
        }
    }
    states[i] = Safe
}

func eventualSafeNodes(graph [][]int) []int {
    states := make([]int, len(graph))
    res := []int{}
    for i, _ := range states {
        dfs(i, states, graph)
    }
    for i, v:= range states {
        if v == Safe {
            res = append(res, i)
        }
    }
    return res
}

  • Solution: topologicalsort + DFS
// https://code.dennyzhang.com/find-eventual-safe-states
// Basic Ideas: topologicalsort + dfs
//
// Detect all cycles in a directed graph
//
// Key Observation: Nodes with no outgoing edges are eventually safe
//
// Complexity: Time O(n+w), Space O(n+w)
func dfs(i int, degrees []int, rEdges map[int]map[int]bool) {
    // skip for visited or unqualified nodes
    if degrees[i] != 0 {
        return
    }
    degrees[i] = -1 // mark node as visited
    for j, _ := range rEdges[i] {
        degrees[j]--
        dfs(j, degrees, rEdges)
    }
}

func eventualSafeNodes(graph [][]int) []int {
    rEdges := map[int]map[int]bool{}
    degrees := make([]int, len(graph))
    for i, l := range graph {
        for _, j := range l {
            // i->j
            if _, ok := rEdges[j]; !ok {
                rEdges[j] = map[int]bool{}
            }
            if ! rEdges[j][i] {
                rEdges[j][i] = true
                degrees[i]++
            }
        }
    }
    for i, _ := range degrees {
        dfs(i, degrees, rEdges)
    }
    res := []int{}
    for i, v:= range degrees {
        if v == -1 {
            res = append(res, i)
        }
    }
    return res
}

  • Solution: topologicalsort + BFS
// https://code.dennyzhang.com/find-eventual-safe-states
// Basic Ideas: topologicalsort + BFS
//
// Detect all cycles in a directed graph
//
// Key Observation: Nodes with no outgoing edges are eventually safe
//
// Complexity: Time O(n+w), Space O(n+w)
func eventualSafeNodes(graph [][]int) []int {
    // There might be duplicate edges, so we don't use map[int][]int{}
    rEdges := map[int]map[int]bool{}
    degrees := make([]int, len(graph))
    for i, l := range graph {
        for _, j := range l {
            // i->j
            if _, ok := rEdges[j]; !ok {
                rEdges[j] = map[int]bool{}
            }
            if ! rEdges[j][i] {
                rEdges[j][i] = true
                degrees[i]++
            }
        }
    }
    queue := []int{}
    for i, v := range degrees {
        if v == 0 {
            queue = append(queue, i)
        }
    }
    for len(queue)>0 {
        l := []int{}
        for _, i := range queue {
            for j, _ := range rEdges[i] {
                degrees[j]--
                if degrees[j] == 0 {
                    l = append(l, j)
                }
            }
        }
        queue = l
    }
    res := []int{}
    for i, v:= range degrees {
        if v==0 {
            res = append(res, i)
        }
    }
    return res
}

  • Solution: topologicalsort + BFS + extra boolean array
// https://code.dennyzhang.com/find-eventual-safe-states
// Basic Ideas: topologicalsort + BFS
//
// Detect all cycles in a directed graph
//
// Key Observation: Nodes with no outgoing edges are eventually safe
//
// Complexity: Time O(n+w), Space O(n+w)
func eventualSafeNodes(graph [][]int) []int {
    // There might be duplicate edges, so we don't use map[int][]int{}
    rEdges := map[int]map[int]bool{}
    degrees := make([]int, len(graph))
    nodes := make([]bool, len(graph))
    for i, l := range graph {
        for _, j := range l {
            // i->j
            if _, ok := rEdges[j]; !ok {
                rEdges[j] = map[int]bool{}
            }
            if ! rEdges[j][i] {
                rEdges[j][i] = true
                degrees[i]++
            }
        }
    }
    queue := []int{}
    for i, v := range degrees {
        if v == 0 {
            queue = append(queue, i)
            nodes[i] = true
        }
    }
    for len(queue)>0 {
        l := []int{}
        for _, i := range queue {
            for j, _ := range rEdges[i] {
                degrees[j]--
                if degrees[j] == 0 {
                    l = append(l, j)
                    nodes[j] = true
                }
            }
        }
        queue = l
    }
    res := []int{}
    for i, b := range nodes {
        if b {
            res = append(res, i)
        }
    }
    return res
}
linkedin
github
slack

Post Views: 10
Posted in HardTagged #graph, colorgraph, topologicalsort

Post navigation

LeetCode: Similar RGB Color
LintCode: The Biggest Score On The Tree

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.