PPractick

DSA interview question

Find Eventual Safe States

Hard · Data structures · Topics: graph, dfs, topological sort

The problem

A workflow engine models states as a directed graph. A state with no outgoing transitions is terminal. A state is safe if every possible path from it eventually reaches a terminal state, meaning no path can get trapped in a loop forever. Return all safe states in increasing order. Work backwards from the terminal states. Reverse every edge and run Kahn's algorithm on out-degrees: a node becomes safe once all of its outgoing edges lead to nodes already known to be safe.

Example: [[1,2], [2,3], [5], [0], [5], [], []] → [2, 4, 5, 6].

Function signature

vector<int> eventualSafeNodes(const vector<vector<int>>& graph);  // sorted ascending

Test cases

Input (adjacency list)OutputExplanation
[[1,2],[2,3],[5],[0],[5],[],[]][2, 4, 5, 6]0, 1, 3 can loop
[[1,2,3,4],[1,2],[3,4],[0,4],[]][4]Everything else reaches a loop
[[1],[2],[]][0, 1, 2]A chain to a terminal
[[0]][]A self-loop is never safe
[[]][0]

(Confirm: the graph is directed and may contain self-loops; terminal nodes are safe.)

How interviewers phrase it

Clarifying questions to ask

  1. Must every path be safe, or just one? (Every path.)
  2. Are terminal nodes safe? (Yes.)
  3. Self-loops? (Possible, and they make the node unsafe.)

Follow-ups to expect

  1. "Why reverse the graph?"
  2. "Why count out-degrees?"
  3. "DFS alternative?"
  4. "Which nodes are unsafe?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in