Find Eventual Safe States

Find the nodes of a directed graph from which every path you can follow comes to an end.

A directed graph has n nodes, numbered 0 to n - 1, and graph[i] lists the nodes that node i has an arrow to. A node with no arrows out is a terminal node. A node is safe if every path that starts there, following arrows, ends at a terminal node. Return all safe nodes in ascending order.

Example 1
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Explanation: 5 and 6 are terminal. 2 and 4 lead only to 5. 0, 1 and 3 can loop 0 → 1 → 3 → 0 forever.
Example 2
Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]
Output: [4]
Solution

The Idea

Picture a town of one-way streets. Each numbered crossing is a node, and each one-way street is an arrow from one crossing to another. A driver who keeps following streets either reaches a dead end, where no street leads out, or keeps driving forever. A crossing is safe if, whatever turns the driver takes from there, the drive always stops at a dead end.

The input already lists the streets crossing by crossing. In Example 1, graph[0] = [1,2] says node 0 has arrows to 1 and 2, and graph[5] = [] says node 5 has none. A list like this, giving the arrows out of each node, is called an adjacency list. Look at the picture below, which draws Example 1 from it.

The graph of Example 1. Nodes 0, 1 and 3 form the cycle 0 to 1 to 3 to 0 and are marked unsafe. Node 2 has an arrow to 5, node 4 has an arrow to 5, and 5 and 6 are terminal. The box labelled safe: every path ends holds 2, 4, 5 and 6.

Nodes 5 and 6, marked terminal, are the dead ends: they have no arrows out, so a path that reaches them stops. Node 2 has one arrow, to 5, and so does node 4. Every path from 2 or 4 therefore stops at 5, which puts 2, 4, 5 and 6 in the box labelled "safe: every path ends".

Now start at 0 and follow the arrows in the box labelled "cycle 0 → 1 → 3 → 0: unsafe": 0 to 1, 1 to 3, 3 back to 0, and round again without end. A path that comes back to a node it has already been on is called a cycle. Node 0 also has an arrow to 2, which ends safely, but that does not help: one path that never ends is enough to make 0 unsafe. The same goes for 1 and 3.

So when does a path never end? The graph has only n nodes, so a path longer than n steps must visit some node twice, and from there it can repeat the same loop forever. That gives the key insight: a node is unsafe exactly when some path from it reaches a cycle. Every other node is safe. The question becomes how to spot cycles, and the nodes that can reach them, without walking every path from every node.

Solution Approach

Turning that idea into code means settling three things: how to notice a cycle, what to remember about each node so it is never searched twice, and what to do with a node found unsafe. A slower way and a backward way come at the end.

Noticing a cycle

How can a search tell that it has gone round a loop? Follow the arrows from a node as deep as they go, one arrow at a time, and come back to try the next arrow only when a path has ended. This order is called depth-first search, or DFS. At any moment it has a current path, the chain of nodes from the start to where it stands.

From 0 in Example 1, the current path grows to 0, 1, 3. The arrow from 3 points to 0, which is still on that path. Reaching a node that is on the current path means the search has come round a cycle, so 3, 1 and 0 can all reach it.

Three states for each node

What does the search need to know about a node it meets? One of three things, kept in an array called state:

  • unvisited: the search has not looked at it yet, so it must explore it.
  • visiting: the search entered it and has not finished it. Meeting it again means unsafe.
  • safe: fully explored, and every arrow out of it led to a safe node. Meeting it again means safe, at once.

A node becomes safe only after all its arrows have led to safe nodes. A terminal node has no arrows to check, so it becomes safe straight away.

Leaving unsafe nodes as visiting

The search is started from each node in turn, 0 first, then 1, and so on. What happens to 0, 1 and 3 once the search from 0 finds the cycle? The search at node 3 answers "unsafe", then so do the searches at nodes 1 and 0, and all three keep the state visiting. Nothing resets it. Later, when the search is started from 1 or 3, it finds visiting and answers "unsafe" without exploring again.

Answering "unsafe" for a node left visiting is correct, because that node was found to reach a cycle earlier. It also means each node is explored at most once, so the whole graph costs one pass.

The slower way: a fresh search from every node

Why not simply search from each node separately? That means starting a new search from each node, with its own record of which nodes are on the current path, and throwing the record away afterwards. It gives the right answer, but the same parts of the graph are searched again from every start. With n nodes and E arrows, that can take about n times (n + E) steps instead of one pass.

Optional: working backward from the terminal nodes

Can the answer be built up from the dead ends instead? Count the arrows out of each node, and for each node also list the nodes that have an arrow into it. Put the terminal nodes, those with a count of 0, in a queue, a waiting line where the first node added is the first taken out. Take a node from the queue, mark it safe, and lower the count of every node with an arrow into it. A node whose count falls to 0 has all its arrows leading to safe nodes, so it joins the queue. Nodes on a cycle, or with a path to one, never reach a count of 0, so they are never marked safe.

Java Solution

The method eventualSafeNodes and its helper isSafe work in these steps:

  1. First, create the array state, with one entry per node, and an empty list result. Java fills a new int array with 0, which is the constant UNVISITED, so every node starts unvisited.
  2. A loop moves i over the nodes from 0 upward and calls isSafe(graph, i, state). Each safe i is added to result. Because i only grows, the list comes out in ascending order.
  3. Inside isSafe, check state[u] for the node u first. If it is not UNVISITED, the answer is already known: SAFE gives true, and VISITING gives false, for a cycle on the current path or a node that failed earlier.
  4. Otherwise, set state[u] to VISITING. A loop then takes each node v that u has an arrow to and calls isSafe on it. On the first false, return false at once, leaving u as VISITING.
  5. If every v was safe, or u had no arrows at all, set state[u] to SAFE and return true.

The main method runs both examples, a node with an arrow to itself, a chain of three nodes with no loop, and two nodes that point at each other.

Java
import java.util.ArrayList;
import java.util.List;

public class FindEventualSafeStates {

    private static final int UNVISITED = 0, VISITING = 1, SAFE = 2;

    public static List<Integer> eventualSafeNodes(int[][] graph) {
        int n = graph.length;
        int[] state = new int[n];                 // every node starts UNVISITED (0)
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (isSafe(graph, i, state)) {
                result.add(i);                    // i grows, so the list is in ascending order
            }
        }
        return result;
    }

    private static boolean isSafe(int[][] graph, int u, int[] state) {
        if (state[u] != UNVISITED) {
            return state[u] == SAFE;              // still VISITING: we came round a cycle
        }
        state[u] = VISITING;
        for (int v : graph[u]) {
            if (!isSafe(graph, v, state)) {
                return false;                     // u stays VISITING, so it counts as unsafe
            }
        }
        state[u] = SAFE;                          // every arrow out of u leads to an end
        return true;
    }

    public static void main(String[] args) {
        int[][] example1 = {{1, 2}, {2, 3}, {5}, {0}, {5}, {}, {}};
        int[][] example2 = {{1, 2, 3, 4}, {1, 2}, {3, 4}, {0, 4}, {}};
        System.out.println(eventualSafeNodes(example1));
        System.out.println(eventualSafeNodes(example2));
        System.out.println(eventualSafeNodes(new int[][] {{0}, {}}));      // 0 points to itself
        System.out.println(eventualSafeNodes(new int[][] {{1}, {2}, {}})); // chain 0 -> 1 -> 2
        System.out.println(eventualSafeNodes(new int[][] {{1}, {0}}));     // 0 and 1 in a loop
    }
}

Running it prints:

Output
[2, 4, 5, 6]
[4]
[1]
[0, 1, 2]
[]

The answer [2, 4, 5, 6] matches the box in the picture. [4] is Example 2, where node 4 is the only terminal node and every other node can reach a cycle: node 1 has an arrow to itself, and 0 → 3 → 0 is a loop too. In [[0],[]], node 0 has an arrow to itself. isSafe(0) marks it visiting, follows the arrow, meets 0 still visiting, and fails, so only 1 is printed.

The chain prints [0, 1, 2], because every path ends at 2. The last line is empty: 0 and 1 point at each other, neither has a way out, and there is no terminal node at all.

The three states matter. A version with a plain true or false "seen" flag, which answers true for any node seen before, treats node 0 as safe when 3 points back to it. That version, run on Example 1, prints [0, 1, 2, 3, 4, 5, 6], every node in the graph.

Complexity

Each node is explored at most once, so the cost depends on the n nodes and the E arrows of the graph.

  • Time: O(n + E), because isSafe runs its loop over a node's arrows only the first time it finds that node unvisited, and every later call returns straight from the state check.
  • Space: O(n), because state and result hold at most one entry per node, and the chain of recursive calls follows one path, which never holds a node twice.

Cycle detection with a queue, close to the backward way above, is shown in Course Schedule.