DSA interview question
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].
vector<int> eventualSafeNodes(const vector<vector<int>>& graph); // sorted ascending
| Input (adjacency list) | Output | Explanation |
|---|---|---|
[[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.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in