29 · Topological Sort

#802 Find Eventual Safe States

Mediumsolve on LeetCode ↗

frequently reported atAmazonGoogle

the problem

In plain words

graph[i] lists the nodes node i points to. A terminal node has no outgoing edges. A node is safe if every path from it ends at a terminal node. Return all safe nodes in ascending order.

in graph = [[1,2],[2,3],[5],[0],[5],[],[]]

out [2,4,5,6]

0, 1, 3 can loop 0→1→3→0 forever.

in graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]

out [4]

  • 1 ≤ n ≤ 10⁴
  • 0 ≤ graph[i].length ≤ n
  • graph[i] is strictly increasing
  • Total edges ≤ 4·10⁴

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #207
      Course Schedule
      Mediumin Topo Sort
    2. #210
      Course Schedule II
      Mediumin Topo Sort
    3. #141
      Linked List Cycle
      Easyin Linked Lists