Safe Transition Path to Disarm State

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

An ordnance-disarming controller operates across n discrete states numbered 0 through n - 1. Each entry [u, v] in edges represents a one-way command transition that moves the controller from state u to state v. The controller begins in state 0 and succeeds as soon as it reaches target.

Certain states listed in unstable trigger immediate failure the moment the controller enters them, so no valid transition sequence may visit or pass through any state in unstable. Transition graphs may also include cycles, self-loops, or dead-end branches; a side loop or dead-end branch elsewhere in the graph does not prevent disarming as long as at least one safe directed route reaches target.

Implement can_defuse(n: int, edges: List[List[int]], unstable: List[int], target: int) -> bool to return True if target can be reached from state 0 via zero or more directed transitions without ever entering an unstable state, and False otherwise.

Examples

Example 1

Input:
  n = 6
  edges = [[0, 1], [1, 5], [0, 2], [2, 3], [3, 2], [3, 5], [2, 4]]
  unstable = [1, 4]
  target = 5
Output:
  True

Walk-through: The direct shortcut 0 -> 1 -> 5 is blocked because state 1 is unstable, and 2 -> 4 enters unstable state 4. However, following 0 -> 2 -> 3 -> 5 visits only safe states (0, 2, 3, 5) and reaches 5 despite the 2 <-> 3 cycle.

Example 2

Input:
  n = 5
  edges = [[0, 1], [1, 4], [0, 2], [2, 3], [4, 3]]
  unstable = [1]
  target = 4
Output:
  False

Walk-through: Route 0 -> 1 -> 4 cannot be used because state 1 is unstable. Route 0 -> 2 -> 3 reaches state 3, and transition [4, 3] points from 4 to 3 rather than from 3 to 4, leaving no safe directed path to 4.

Constraints

  • 2 <= n <= 10^5
  • 0 <= len(edges) <= 2 * 10^5
  • 0 <= u, v, target < n
  • Neither 0 nor target appears in unstable (target may equal 0).

Step-by-step walkthrough

  1. Understand the problem and simplify the rules

    We have n states numbered 0 through n - 1 and a list of one-way transitions [src, dst] meaning we can move from src to dst (never backward unless [dst, src] is also listed). Starting in state 0, we want to know whether there is at least one sequence of transitions that reaches target without ever stepping onto any state listed in unstable.

    Example 1 (target = 5, unstable = [1, 4]):
             +---> [1: UNSTABLE] ---> 5
             |
      0 -----+---> 2 <===> 3 ---> 5 (TARGET)
                   |
                   +---> [4: UNSTABLE]
      Safe route 0 -> 2 -> 3 -> 5 avoids states 1 and 4 completely -> True
    
    Example 2 (target = 4, unstable = [1]):
             +---> [1: UNSTABLE] ---> 4 (TARGET)
             |                        |
      0 -----+---> 2 ---> 3 <---------+  (arrow [4, 3] points into 3, not 4!)
      Blocked! Every path to 4 either crosses state 1 or faces a reverse arrow -> False
    

    Notice how cycles and dead-end branches behave:

    • If every transition out of some state leads only into dead ends or unstable states, no route through it can reach target anyway, so a normal search naturally leaves target unreached along that branch.
    • If a safe state participates in a cycle (such as 2 <-> 3 in Example 1), we do not get trapped forever — as long as visited tracks explored states, the search steps across 2 -> 3 -> 5 cleanly.

    So the entire problem reduces to one clean question: after deleting every unstable state from the graph, is target still reachable from 0?

  2. Why naive path enumeration or repeated sweeps are too slow

    Two obvious first ideas run into trouble on large inputs (n <= 10^5 states and m <= 2 * 10^5 edges):

    1. Listing every possible path from 0: When paths branch and merge (for example, a chain of diamonds 0 -> {1, 2} -> 3 -> {4, 5} -> 6 ...), the number of distinct paths doubles at every diamond and grows exponentially (2^(n/3)). Worse, if the graph contains a loop like 0 -> 2 -> 0, walking paths without remembering visited states loops forever.
    2. Repeatedly scanning the edge list: You could start with reachable = {0} and loop over all m edges again and again, adding dst whenever src is reachable and dst is safe, until a full pass adds nothing new. On a long chain of 10^5 states listed in reverse order, each pass discovers only one new state, costing O(n * m) operations — up to 2 * 10^10 steps.
  3. Core idea: filter out unstable states, then run Breadth-First Search

    We model the system as a directed graph (a network of nodes connected by one-way arrows) and remove all unstable states before searching. Then we explore outward from state 0 using Breadth-First Search (BFS):

    • Keep a FIFO queue (first-in, first-out waiting line, implemented with collections.deque) of safe states to explore, starting with 0.
    • Keep a boolean list visited so the very first time we discover a state, we mark it True and never put it in the queue again.

    Because each of the n states enters the queue at most once, and we scan its outgoing transitions only when it leaves the queue, every state and every edge is processed at most once — O(n + m) time total. Using an iterative queue instead of recursive Depth-First Search (DFS) also avoids hitting Python's default 1000-call recursion limit on a 10^5-state chain.

  4. Phase 1: Mark unstable states and handle immediate base cases

    Checking state in unstable directly on the input list would scan the whole list in O(len(unstable)) time on every edge. Instead, we allocate a boolean lookup table is_unstable of length n so checking any state takes O(1) time.

    We also check two immediate base cases right away: if 0 or target were ever unstable, no safe path could exist; otherwise, if target == 0, we are already at the goal before taking any transition.

    def can_defuse(n: int, edges: List[List[int]], unstable: List[int], target: int) -> bool:
        # Phase 1: Mark unsafe states in a boolean lookup table for O(1) checks.
        # is_unstable[state] is True if entering `state` detonates the bomb, e.g. [False, True, False, False].
        is_unstable = [False] * n
        for state in unstable:
            is_unstable[state] = True
    
        # Defensive guard: if the start or target state itself were unstable, no safe path could exist.
        if is_unstable[0] or is_unstable[target]:
            return False
    
        # If we already start at the target state, zero transitions are needed.
        if target == 0:
            return True
    
  5. Phase 2: Build the safe adjacency list

    Next, we build an adjacency list neighbors, where neighbors[src] is the list of safe states reachable from src in a single transition. If either endpoint src or dst is unstable, we ignore that edge completely — we can never step into an unstable state, and because we never enter one, we can never use an edge out of it either.

    Example 1 raw edges: [0, 1], [1, 5], [0, 2], [2, 3], [3, 2], [3, 5], [2, 4]   with unstable = [1, 4]
    Filtered neighbors:
      neighbors[0] = [2]        ([0, 1] dropped because 1 is unstable)
      neighbors[1] = []         ([1, 5] dropped because 1 is unstable)
      neighbors[2] = [3]        ([2, 4] dropped because 4 is unstable)
      neighbors[3] = [2, 5]
      neighbors[4] = []
      neighbors[5] = []
    
        # Phase 2: Build the directed adjacency list over ONLY the safe states.
        # neighbors[src] holds [dst_1, dst_2, ...] for every safe directed transition src -> dst.
        neighbors: List[List[int]] = []
        for _ in range(n):
            neighbors.append([])
    
        for edge in edges:
            src = edge[0]
            dst = edge[1]
            # Drop any transition touching an unstable state so the search can never enter or cross one.
            if not is_unstable[src] and not is_unstable[dst]:
                neighbors[src].append(dst)
    
  6. Phase 3: Explore safe states with BFS and trace the samples

    Now we run standard BFS starting from 0:

    • Mark visited[0] = True and initialize queue = deque([0]).
    • Pop current_state from the front with queue.popleft() (which runs in O(1) time, unlike list.pop(0) which shifts every remaining element in O(n) time).
    • For each next_state in neighbors[current_state], skip it if visited[next_state] is already True. If next_state == target, we found a safe route and immediately return True. Otherwise, mark visited[next_state] = True right before appending it to queue so duplicate edges or cycles cannot push the same state into the queue multiple times.
    Trace on Example 1 (n = 6, filtered neighbors: 0->[2], 2->[3], 3->[2, 5], target = 5):
      Start:  queue = [0], visited = [T, F, F, F, F, F]
      Step 1: pop 0 -> see 2 (safe, unvisited) -> mark & push 2 -> queue = [2], visited = [T, F, T, F, F, F]
      Step 2: pop 2 -> see 3 (safe, unvisited) -> mark & push 3 -> queue = [3], visited = [T, F, T, T, F, F]
      Step 3: pop 3 -> see 2 (already visited, skip)
                    -> see 5 -> matches target == 5! -> return True immediately
    
    Trace on Example 2 (n = 5, filtered neighbors: 0->[2], 2->[3], 4->[3], target = 4):
      Start:  queue = [0], visited = [T, F, F, F, F]
      Step 1: pop 0 -> see 2 -> mark & push 2 -> queue = [2]
      Step 2: pop 2 -> see 3 -> mark & push 3 -> queue = [3]
      Step 3: pop 3 -> neighbors[3] is [] -> nothing added
      End:    queue is empty -> return False
    
        # Phase 3: Breadth-first search (BFS) from state 0 to check if `target` is reachable.
        # visited[state] becomes True the moment `state` enters `queue` so cycles never re-queue it.
        visited = [False] * n
        visited[0] = True
        # queue: FIFO deque of safe states waiting to have their outgoing edges explored, e.g. deque([0])
        queue = deque([0])
    
        while queue:
            current_state = queue.popleft()
            for next_state in neighbors[current_state]:
                if visited[next_state]:
                    continue
                if next_state == target:
                    return True
                visited[next_state] = True
                queue.append(next_state)
    
        return False
    
  7. Complete solution

    Putting all three phases together gives the complete O(n + m) solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    
    def can_defuse(n: int, edges: List[List[int]], unstable: List[int], target: int) -> bool:
        # Phase 1: Mark unsafe states in a boolean lookup table for O(1) checks.
        # is_unstable[state] is True if entering `state` detonates the bomb, e.g. [False, True, False, False].
        is_unstable = [False] * n
        for state in unstable:
            is_unstable[state] = True
    
        # Defensive guard: if the start or target state itself were unstable, no safe path could exist.
        if is_unstable[0] or is_unstable[target]:
            return False
    
        # If we already start at the target state, zero transitions are needed.
        if target == 0:
            return True
    
        # Phase 2: Build the directed adjacency list over ONLY the safe states.
        # neighbors[src] holds [dst_1, dst_2, ...] for every safe directed transition src -> dst.
        neighbors: List[List[int]] = []
        for _ in range(n):
            neighbors.append([])
    
        for edge in edges:
            src = edge[0]
            dst = edge[1]
            # Drop any transition touching an unstable state so the search can never enter or cross one.
            if not is_unstable[src] and not is_unstable[dst]:
                neighbors[src].append(dst)
    
        # Phase 3: Breadth-first search (BFS) from state 0 to check if `target` is reachable.
        # visited[state] becomes True the moment `state` enters `queue` so cycles never re-queue it.
        visited = [False] * n
        visited[0] = True
        # queue: FIFO deque of safe states waiting to have their outgoing edges explored, e.g. deque([0])
        queue = deque([0])
    
        while queue:
            current_state = queue.popleft()
            for next_state in neighbors[current_state]:
                if visited[next_state]:
                    continue
                if next_state == target:
                    return True
                visited[next_state] = True
                queue.append(next_state)
    
        return False
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture the bomb defusal system as a building of numbered rooms (0 through n - 1) connected by one-way doors (edges), where you start in room 0 and want to reach the exit (target) without ever stepping into an alarmed room (unstable). If you take a marker and cross every alarmed room — along with all doors leading into or out of it — off your floor plan before you start walking, the problem becomes a simple map question: do the remaining one-way doors still let you walk from room 0 to target? We answer that using Breadth-First Search (BFS), a graph traversal algorithm that explores reachable nodes wave by wave (first 1 step away, then 2 steps away, and so on) using a first-in, first-out (FIFO) queue (a waiting line where the earliest item added is the first one removed) and a visited checklist so no room is ever explored twice.

Why do simpler approaches fall short? Trying to trace every possible route from 0 one path at a time can get stuck forever in a cycle (a loop of transitions that returns to an earlier state, such as 0 -> 2 -> 0) or blow up into exponentially many paths when routes branch and rejoin. Even a loop-safe brute force that repeatedly scans the full edge list to expand a set of reachable states can take n passes of m edges each, costing O(n * m) operations — up to 2 * 10^10 steps when n = 10^5 and m = 2 * 10^5. Checking state in unstable directly on the input list inside the search is another performance trap, turning a constant-time check into an O(n) linear scan on every transition.

Let's walk through Example 1 (n = 6, edges = [[0, 1], [1, 5], [0, 2], [2, 3], [3, 2], [3, 5], [2, 4]], unstable = [1, 4], target = 5):

1. Mark unstable states:  is_unstable = [False, True, False, False, True, False]
2. Filter safe edges:     [0, 1], [1, 5], and [2, 4] are dropped because states 1 and 4 are unstable.
                          Adjacency list -> 0: [2], 1: [], 2: [3], 3: [2, 5], 4: [], 5: []
3. BFS from state 0:
   - Start: queue = [0], visited = [T, F, F, F, F, F]
   - Pop 0: neighbor 2 is unvisited -> mark visited[2] = True, queue = [2]
   - Pop 2: neighbor 3 is unvisited -> mark visited[3] = True, queue = [3]
   - Pop 3: neighbor 2 is already visited (skip cycle);
            neighbor 5 -> equals target (5)! Return True immediately (path 0 -> 2 -> 3 -> 5).

Complexity

Let n be the number of states and m = len(edges) be the number of directed transitions.

  • Time: O(n + m). Initializing is_unstable, neighbors, and visited touches each of the n states a constant number of times (O(n)), building neighbors inspects each of the m edges once (O(m)), and BFS pushes/pops each state at most once (O(n)) while scanning each safe outgoing edge at most once (O(m)).
  • Space: O(n + m). The adjacency list (an array of lists where slot u stores all outgoing neighbors of node u) stores at most m safe transitions across n buckets, while is_unstable, visited, and queue each hold at most n entries.

Edge cases

  • Start equals target (target == 0): No transitions are needed; the empty path already starts on target and enters zero unstable states, so we return True immediately.
  • No edges (edges = []) or disconnected target: The queue empties after popping 0, and the function cleanly returns False.
  • One-way transitions ([1, 0] when target = 1): Because edges are directed, [1, 0] adds 0 to neighbors[1] only, leaving neighbors[0] empty and returning False.
  • Unstable state acting as a bridge (0 -> 1 -> 2 with 1 unstable): Both 0 -> 1 and 1 -> 2 are excluded when building neighbors, so state 1 can never bridge a path to target.
  • Cycles, self-loops ([0, 0]), and duplicate edges: Marking visited[state] = True as soon as a state enters the queue prevents re-queueing and guarantees termination.
  • Duplicate entries in unstable: Setting is_unstable[state] = True multiple times is idempotent (doing it twice has the exact same effect as doing it once).
  • Deep chains (10^5 states in a line): Because BFS uses an explicit deque loop rather than function recursion, it never triggers a RecursionError.

Common mistakes

  • Treating edges as undirected: Adding both neighbors[src].append(dst) and neighbors[dst].append(src) lets the search walk backward through one-way transitions.
  • Testing next_state in unstable on the raw list: List membership scans element by element in O(len(unstable)) time, degrading overall runtime to O(m * n). Always convert unstable to a boolean list of size n (or a set).
  • Using list.pop(0) instead of deque.popleft(): Removing index 0 from a Python list shifts every remaining element left in O(n) time, which can push BFS to O(n^2).
  • Marking visited on pop instead of on push: If you wait until a state is popped to mark visited, many incoming edges can push hundreds of duplicate copies of the same state into the queue before the first copy is popped.
  • Using recursive DFS on n = 10^5: Python's default recursion depth limit is 1000, so a simple chain 0 -> 1 -> 2 -> ... -> 99999 crashes with RecursionError.
  • Rejecting safe states just because they touch a cycle: In Example 1, states 2 and 3 form a 2 <-> 3 loop, yet 0 -> 2 -> 3 -> 5 still reaches 5 safely because visited prevents repeating 2.
  • Forgetting target == 0: Checking next_state == target only when inspecting neighbors misses the case where we start directly on target.

Alternative approaches

  • Iterative Depth-First Search (DFS) with a stack: Replace deque.popleft() with stack.pop() on a plain Python list (a LIFO stack, where the last item pushed is the first item popped). It explores deep along one branch before backtracking and achieves the exact same O(n + m) time and space without recursion limits.
  • Bidirectional BFS: Run two simultaneous BFS frontiers — one forward from 0 along src -> dst edges and one backward from target along reversed dst -> src edges — stopping as soon as the two frontiers touch. Worst-case complexity stays O(n + m), but on wide, branching graphs it typically visits far fewer states.
  • Why Union-Find does NOT work here: Union-Find (Disjoint Set Union, a data structure that merges connected groups in near-constant time) only tracks symmetric, two-way connectivity, so it cannot distinguish 0 -> 1 from 1 -> 0 in a directed graph.

Follow-up questions

  • Suppose certain transitions remain locked until the controller has visited specific prerequisite 'unlock' states—how would you adapt the search? Expand each search node from state to a pair (state, unlock_mask), where unlock_mask is a bitmask (an integer whose i-th binary bit is 1 if prerequisite state i has already been visited and 0 otherwise). Entering an unlock state sets its bit via bitwise OR, and a locked transition is traversed only when its required bit in unlock_mask is 1. With k distinct prerequisites there are n * 2^k augmented (state, unlock_mask) pairs, so standard BFS over those pairs runs in O((n + m) * 2^k) time — for a single prerequisite (k = 1), that is only 2n states ("before unlocking" and "after unlocking").
  • How would you cut down the RAM footprint of the graph representation and visited tracking if there were tens of millions of states? Python objects carry heavy per-object overhead (each int takes 28 bytes and each list header takes 56+ bytes), so replace the list-of-lists adjacency structure with Compressed Sparse Row (CSR) format — two flat typed array('i') buffers: an offsets array of length n + 1 and a contiguous targets array of length m, where node u's outgoing neighbors sit in targets[offsets[u] : offsets[u + 1]]. Likewise, pack visited and is_unstable into a bytearray (1 byte per state) or a bitset (1 bit per state, 8 states per byte), shrinking memory from gigabytes to tens of megabytes. Whenever transitions are defined by an implicit transition rule rather than an explicit edge list, compute neighbors on the fly during BFS so m edges never need to be stored at all.
  • How does the algorithm change if you must return the minimum number of transitions (or minimum total transition weight) needed to reach target? When every transition costs 1 step, BFS already explores states in non-decreasing order of distance, so recording dist[next_state] = dist[current_state] + 1 (and optionally parent[next_state] = current_state to reconstruct the route) when next_state enters the queue yields the minimum transition count in O(n + m) time. When transitions carry arbitrary non-negative weights, replace the FIFO queue with Dijkstra's algorithm — using a min-heap (a priority queue that pops the state with the lowest accumulated cost in logarithmic time) to find the minimum-weight safe route in O((n + m) log n) time.

Follow-up questions

Similar questions

More Mithril interview questions

All 4 Mithril questions →