Python coding

States that always halt

A program is a state machine with states 0 to n - 1, where n = len(moves). moves[i] lists the states it can jump to from state i; the list may repeat a state or include i itself. A state with no moves halts. A state is safe if the program is sure to halt from it whichever moves it takes: no sequence of moves from it goes on forever. Return every safe state in increasing order.

Besides the tests, one large input (2,600 states, 5,200 moves) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

  • safe_states([[1],[2],[0,3],[],[3],[4,1]]) → [3,4]
  • safe_states([[],[0],[1,1]]) → [0,1,2]
  • safe_states([[0]]) → []
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

A state is safe exactly when every one of its moves leads to a safe state. Halting states are safe for free: start from them and work backwards.

Hint 2

Reverse every move and run Kahn's algorithm on out-degrees: when a state's last unproven move is proven safe, queue it. States never queued can reach a loop.

Solution and why it works
pythonO(n + E), E = total moves · O(n + E)
from collections import deque


def safe_states(moves: list[list[int]]) -> list[int]:
    n = len(moves)
    came_from = [[] for _ in range(n)]
    unproven = [len(m) for m in moves]       # moves not yet known to lead somewhere safe
    for u, targets in enumerate(moves):
        for v in targets:
            came_from[v].append(u)           # reversed edge v -> u
    queue = deque(u for u in range(n) if unproven[u] == 0)   # halting states
    safe = [False] * n
    while queue:
        v = queue.popleft()
        safe[v] = True
        for u in came_from[v]:
            unproven[u] -= 1
            if unproven[u] == 0:             # every move from u is now proven safe
                queue.append(u)
    return [u for u in range(n) if safe[u]]

This is Kahn's algorithm run backwards. Count each state's unproven moves (its out-degree) and queue the halting states; popping a safe state takes one unproven move off every state that jumps into it, and reaching zero proves that state safe. A state on a loop, or one with a move toward a loop, never reaches zero. Traps: one safe move is not enough, all of them must be; and a separate DFS from every state is O(n·(n + E)).