AlgoMaster Logo

Find Eventual Safe States

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. DFS with Cycle Detection

Intuition:

The idea here is to perform a DFS on each node and track if it can lead to a cycle or not. A "cycle" here indicates that the node is not safe as from that node, there exists a path that returns to itself. We will use a state array for each node to keep track of:

  • 0 if the node has not been visited.
  • 1 if the node is visiting (visited while its path not finished).
  • 2 if the node is safe (visited and no cycle through it).

On visiting a node, if we encounter another node that is in the visiting state, it means there's a cycle.

Code:

2. Reverse Graph and Topological Sort

Intuition:

The second approach involves inverting the edges of the graph. A node is safe if it eventually leads to a terminal node, which is an outdegree of 0 in the original graph. By reversing the graph's edges, terminal nodes convert to indegree 0 nodes.

Use a queue to perform a Kahn's algorithm variant of topological sort. Begin by enqueueing nodes with outdegree 0 (become indegree 0 in reversed graph) and iteratively remove them, updating neighbors' indegree count.

Code: