Payments app~25 min2s · 256 MBtarget O(n + m) time, O(n + m) spaceclassic twin: lc-802dfs
You work on a payments app. A payment moves between states such as created, authorised, retrying and settled. The states are numbered 0 to n - 1.
A move [a, b] means a payment in state a can move to state b. A state with no move out is final: the payment is done there. A state is safe when every possible path from it ends in a final state.
A state is unsafe when some path never ends, because it circulates in a loop of retries. The risk team wants a list of the safe states.
Write safe_states(n, moves).
n is the number of states.moves[i] = [a, b] is a move from state a to state b. A state can move to itself, and a move can appear more than once.[] when no state is safe.Input: n = 6, moves = [[0, 1], [1, 0], [2, 3], [3, 4], [2, 0]]
Output: [3, 4, 5]States 0 and 1 loop. State 2 can reach the loop through the move to 0. States 3, 4 and 5 always end. Walk with a path and mark each state: 0 is new, 1 is on the path, 2 is safe, 3 is unsafe.
| Step | What happens | Path after | Marks of states 0 to 5 |
|---|---|---|---|
| 1 | start at 0 | 0 | 1, 0, 0, 0, 0, 0 |
| 2 | 0 moves to 1 | 0, 1 | 1, 1, 0, 0, 0, 0 |
| 3 | 1 moves to 0, which is on the path | 0, 1 | 1, 3, 0, 0, 0, 0 |
| 4 | 1 leaves and tells 0; then 0 leaves | 3, 3, 0, 0, 0, 0 | |
| 5 | start at 2; 2 moves to 3; 3 moves to 4 | 2, 3, 4 | 3, 3, 1, 1, 1, 0 |
| 6 | 4 has no move left and 3 has none left: both are safe | 2 | 3, 3, 1, 2, 2, 0 |
| 7 | 2 moves to 0, which is unsafe | 2 | 3, 3, 3, 2, 2, 0 |
| 8 | 2 leaves; state 5 starts and is safe | 3, 3, 3, 2, 2, 2 |
Input: n = 3, moves = []
Output: [0, 1, 2]No state has a move, so every state is final and safe.
Input: n = 3, moves = [[0, 0], [1, 0], [2, 1]]
Output: []State 0 moves to itself, which is a loop. States 1 and 2 can reach it.
1 ≤ n ≤ 100,0000 ≤ len(moves) ≤ 100,000, and every row is [a, b] with 0 ≤ a, b < nThere can be 100,000 states and 100,000 moves. Marking safe states by going over every state again and again takes up to n passes of n + m steps: about 20 billion. The answer must visit each state and move a few times: n + m.