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^50 <= len(edges) <= 2 * 10^50 <= u, v, target < n- Neither
0nortargetappears inunstable(targetmay equal0).
Step-by-step walkthrough
Understand the problem and simplify the rules
We have
nstates numbered0throughn - 1and a list of one-way transitions[src, dst]meaning we can move fromsrctodst(never backward unless[dst, src]is also listed). Starting in state0, we want to know whether there is at least one sequence of transitions that reachestargetwithout ever stepping onto any state listed inunstable.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 -> FalseNotice 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
targetanyway, so a normal search naturally leavestargetunreached along that branch. - If a safe state participates in a cycle (such as
2 <-> 3in Example 1), we do not get trapped forever — as long asvisitedtracks explored states, the search steps across2 -> 3 -> 5cleanly.
So the entire problem reduces to one clean question: after deleting every unstable state from the graph, is
targetstill reachable from0?- If every transition out of some state leads only into dead ends or unstable states, no route through it can reach
Why naive path enumeration or repeated sweeps are too slow
Two obvious first ideas run into trouble on large inputs (
n <= 10^5states andm <= 2 * 10^5edges):- Listing every possible path from
0: When paths branch and merge (for example, a chain of diamonds0 -> {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 like0 -> 2 -> 0, walking paths without remembering visited states loops forever. - Repeatedly scanning the edge list: You could start with
reachable = {0}and loop over allmedges again and again, addingdstwheneversrcis reachable anddstis safe, until a full pass adds nothing new. On a long chain of10^5states listed in reverse order, each pass discovers only one new state, costingO(n * m)operations — up to2 * 10^10steps.
- Listing every possible path from
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
0using Breadth-First Search (BFS):- Keep a FIFO queue (first-in, first-out waiting line, implemented with
collections.deque) of safe states to explore, starting with0. - Keep a boolean list
visitedso the very first time we discover a state, we mark itTrueand never put it in the queue again.
Because each of the
nstates 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 default1000-call recursion limit on a10^5-state chain.- Keep a FIFO queue (first-in, first-out waiting line, implemented with
Phase 1: Mark unstable states and handle immediate base cases
Checking
state in unstabledirectly on the input list would scan the whole list inO(len(unstable))time on every edge. Instead, we allocate a boolean lookup tableis_unstableof lengthnso checking any state takesO(1)time.We also check two immediate base cases right away: if
0ortargetwere ever unstable, no safe path could exist; otherwise, iftarget == 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 TruePhase 2: Build the safe adjacency list
Next, we build an adjacency list
neighbors, whereneighbors[src]is the list of safe states reachable fromsrcin a single transition. If either endpointsrcordstis 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)Phase 3: Explore safe states with BFS and trace the samples
Now we run standard BFS starting from
0:- Mark
visited[0] = Trueand initializequeue = deque([0]). - Pop
current_statefrom the front withqueue.popleft()(which runs inO(1)time, unlikelist.pop(0)which shifts every remaining element inO(n)time). - For each
next_stateinneighbors[current_state], skip it ifvisited[next_state]is alreadyTrue. Ifnext_state == target, we found a safe route and immediately returnTrue. Otherwise, markvisited[next_state] = Trueright before appending it toqueueso 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- Mark
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). Initializingis_unstable,neighbors, andvisitedtouches each of thenstates a constant number of times (O(n)), buildingneighborsinspects each of themedges 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 slotustores all outgoing neighbors of nodeu) stores at mostmsafe transitions acrossnbuckets, whileis_unstable,visited, andqueueeach hold at mostnentries.
Edge cases
- Start equals target (
target == 0): No transitions are needed; the empty path already starts ontargetand enters zero unstable states, so we returnTrueimmediately. - No edges (
edges = []) or disconnected target: The queue empties after popping0, and the function cleanly returnsFalse. - One-way transitions (
[1, 0]whentarget = 1): Because edges are directed,[1, 0]adds0toneighbors[1]only, leavingneighbors[0]empty and returningFalse. - Unstable state acting as a bridge (
0 -> 1 -> 2with1unstable): Both0 -> 1and1 -> 2are excluded when buildingneighbors, so state1can never bridge a path totarget. - Cycles, self-loops (
[0, 0]), and duplicate edges: Markingvisited[state] = Trueas soon as a state enters the queue prevents re-queueing and guarantees termination. - Duplicate entries in
unstable: Settingis_unstable[state] = Truemultiple times is idempotent (doing it twice has the exact same effect as doing it once). - Deep chains (
10^5states in a line): Because BFS uses an explicitdequeloop rather than function recursion, it never triggers aRecursionError.
Common mistakes
- Treating edges as undirected: Adding both
neighbors[src].append(dst)andneighbors[dst].append(src)lets the search walk backward through one-way transitions. - Testing
next_state in unstableon the rawlist: List membership scans element by element inO(len(unstable))time, degrading overall runtime toO(m * n). Always convertunstableto a boolean list of sizen(or aset). - Using
list.pop(0)instead ofdeque.popleft(): Removing index0from a Pythonlistshifts every remaining element left inO(n)time, which can push BFS toO(n^2). - Marking
visitedon pop instead of on push: If you wait until a state is popped to markvisited, 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 is1000, so a simple chain0 -> 1 -> 2 -> ... -> 99999crashes withRecursionError. - Rejecting safe states just because they touch a cycle: In Example 1, states
2and3form a2 <-> 3loop, yet0 -> 2 -> 3 -> 5still reaches5safely becausevisitedprevents repeating2. - Forgetting
target == 0: Checkingnext_state == targetonly when inspecting neighbors misses the case where we start directly ontarget.
Alternative approaches
- Iterative Depth-First Search (DFS) with a stack: Replace
deque.popleft()withstack.pop()on a plain Pythonlist(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 sameO(n + m)time and space without recursion limits. - Bidirectional BFS: Run two simultaneous BFS frontiers — one forward from
0alongsrc -> dstedges and one backward fromtargetalong reverseddst -> srcedges — stopping as soon as the two frontiers touch. Worst-case complexity staysO(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 -> 1from1 -> 0in 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
stateto a pair(state, unlock_mask), whereunlock_maskis a bitmask (an integer whosei-th binary bit is1if prerequisite stateihas already been visited and0otherwise). Entering an unlock state sets its bit via bitwise OR, and a locked transition is traversed only when its required bit inunlock_maskis1. Withkdistinct prerequisites there aren * 2^kaugmented(state, unlock_mask)pairs, so standard BFS over those pairs runs inO((n + m) * 2^k)time — for a single prerequisite (k = 1), that is only2nstates ("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
inttakes 28 bytes and eachlistheader takes 56+ bytes), so replace the list-of-lists adjacency structure with Compressed Sparse Row (CSR) format — two flat typedarray('i')buffers: anoffsetsarray of lengthn + 1and a contiguoustargetsarray of lengthm, where nodeu's outgoing neighbors sit intargets[offsets[u] : offsets[u + 1]]. Likewise, packvisitedandis_unstableinto abytearray(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 somedges 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 recordingdist[next_state] = dist[current_state] + 1(and optionallyparent[next_state] = current_stateto reconstruct the route) whennext_stateenters the queue yields the minimum transition count inO(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 inO((n + m) log n)time.
Follow-up questions
- Suppose certain transitions remain locked until the controller has visited specific prerequisite 'unlock' states—how would you adapt the search?
- How would you cut down the RAM footprint of the graph representation and visited tracking if there were tens of millions of states?
- How does the algorithm change if you must return the minimum number of transitions (or minimum total transition weight) needed to reach target?
Similar questions
- Lower Flat Programs to Triad IR
- Fix Priority Preemption in GPU Leasing
- Hybrid-Cloud GPU Cluster Scheduling Service
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses