Worst-Case Pursuit Time on an Undirected Graph
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
An undirected simple graph has n vertices numbered 0 through n - 1 and a list of undirected edges. Two players—tom (the pursuer) and jerry (the evader)—start at vertices tom and jerry respectively, and both players have complete knowledge of the graph and both current positions at all times.
If tom == jerry initially, capture happens immediately at 0 seconds. Otherwise, play advances in discrete seconds 1, 2, 3, ..., where each second consists of two sequential moves:
- Jerry's move: Jerry either traverses one edge to an adjacent vertex or stays at his current vertex.
- Tom's move: If the two players do not already share a vertex, Tom either traverses one edge to an adjacent vertex or stays at his current vertex.
Because turns within each second are sequential rather than simultaneous, players never cross past each other along an edge without meeting; the game ends the instant both occupy the same vertex, and the elapsed time is the number of the second in which they meet (for instance, meeting on either player's move during the first second counts as 1 second).
Tom plays optimally to minimize the capture time, while Jerry plays optimally to maximize it (or avoid capture forever). Implement
def guaranteed_capture_time(n: int, edges: List[List[int]], tom: int, jerry: int) -> int:
returning the smallest number of seconds within which Tom can guarantee catching Jerry against every legal strategy by Jerry, or -1 if Jerry can evade capture indefinitely. Note that general inputs may be disconnected or contain cycles: be ready to explain why comparing shortest-path distances from tom and jerry alone fails on cyclic graphs, and what structural graph restriction or altered objective would make a shortest-path comparison exact.
Examples
Example 1
Input: n = 5, edges = [[0, 1], [1, 2], [2, 3], [2, 4]], tom = 0, jerry = 1
Output: 3
Although Tom and Jerry start on adjacent vertices (0 and 1), Jerry acts first in Second 1 and retreats 1 -> 2 while Tom advances 0 -> 1. In Second 2, Jerry slips into one of the leaf branches (2 -> 3 or 2 -> 4) while Tom advances 1 -> 2. In Second 3, Jerry has no safe neighbor left from the leaf, so Tom steps onto Jerry's leaf and finishes the capture in 3 seconds.
Example 2
Input: n = 5, edges = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 1]], tom = 0, jerry = 3
Output: -1
Vertices 1 - 2 - 3 - 4 - 1 form a chordless 4-cycle with stem 0 - 1. Even after Tom enters the cycle, from any vertex Tom occupies on the 4-cycle there is always a cycle neighbor of Jerry outside Tom's 1-step reach, allowing Jerry to evade indefinitely.
Example 3
Input: n = 4, edges = [[0, 1], [0, 2], [1, 2], [1, 3], [2, 3]], tom = 0, jerry = 3
Output: 2
Vertices 0, 1, 2, 3 form a diamond (a 4-cycle with diagonal chord [1, 2]). In Second 1, stepping to 1 or 2 would let Tom capture immediately from 0, so Jerry stays on 3 while Tom moves 0 -> 1. Because 1 is adjacent to 0, 2, and 3 simultaneously, every move available to Jerry from 3 in Second 2 (3, 1, or 2) lies within one step of 1, guaranteeing capture in 2 seconds.
Constraints
1 <= n <= 50, with vertices labeled0throughn - 1.edgescontains unique undirected pairs[u, v]of distinct valid vertices (0 <= u, v < n,u != v).0 <= tom, jerry < n.- The graph is not necessarily connected or acyclic, and staying in place is always a legal move for either player.
Step-by-step walkthrough
Restate the turn order and clock rules
We are given an undirected graph on
n <= 50vertices (0throughn - 1), Tom's starting vertex, and Jerry's starting vertex. Both players have full visibility of the graph and current positions. Iftom == jerryinitially, capture happens immediately at0seconds.Otherwise, time ticks in discrete seconds (
1, 2, 3, ...), and every single second splits into two sequential half-turns:Start of Second s: Mid-Second s: End of Second s: (Tom at t, Jerry at j) -----> (Tom at t, Jerry at j') -----> (Tom at t', Jerry at j') 1. Jerry moves 2. Tom moves (neighbor or stay) (neighbor or stay)Capture happens the instant both occupy the same vertex, and the game score is the second
sin which capture occurs. Tom chooses moves to minimizes; Jerry chooses moves to maximizes(or force-1, infinite evasion).Two observations immediately simplify the rules:
- "Jerry moves first" changes adjacent starts. Look at Example 1, the 5-vertex tree
0 - 1 - 2branching to leaves3and4withtom = 0andjerry = 1. Even though they start next to each other, in Second 1 Jerry retreats1 -> 2before Tom moves while Tom follows0 -> 1; in Second 2 Jerry slips into leaf3(or4) while Tom reaches2; and Tom only corners Jerry in Second 3 (2 -> 3). So the answer is3, not1. - Jerry never benefits from walking onto Tom. Whenever
t != j, Jerry is always allowed to stay onj, which survives Jerry's half-turn and forces Tom to take his half-turn in the same seconds(giving capture time>= s, whereas walking onto Tom ends immediately in seconds). Thus every optimal capture happens on Tom's half-turn.
- "Jerry moves first" changes adjacent starts. Look at Example 1, the 5-vertex tree
Why the BFS distance shortcut fails on general graphs
A tempting shortcut is to run BFS (breadth-first search)—level-by-level shortest-path exploration—from
tom(d_tom) and fromjerry(d_jerry), find every vertexvthat Jerry can reach strictly before Tom (d_jerry(v) < d_tom(v)), and guess:D = max { d_tom(v) for all v where d_jerry(v) < d_tom(v) }On any graph,
Dis a valid lower bound: Jerry can walk a shortest path to that vertexvwithout ever being adjacent to Tom along the way, then sit onvuntil Tom walksd_tom(v)edges to reach it. However,Dfails as an exact solver on general graphs for two distinct reasons:Counterexample 1: Stem + 4-cycle (Example 2) Counterexample 2: Triangle with ears (finite, slower) 0 --- 1 --- 2 3 | | tom = 0, jerry = 3 / \ 4 --- 3 d_tom(3) = 3 => D = 3 0---1 True answer = -1! / \ / \ 4---2---5 Around 1-2-3-4-1, Jerry always tom = 3, jerry = 0 steps to a cycle neighbor out BFS shortcut gives D = 2, of Tom's 1-step reach forever. yet Jerry dodges for 3 seconds!- Chordless cycles of length
>= 4allow infinite evasion (-1). In Example 2 (0 - 1attached to1 - 2 - 3 - 4 - 1,tom = 0, jerry = 3),D = 3, yet around the 4-cycle Jerry always has a neighbor outside Tom's 1-step reach. (Contrast this with Example 3, where adding chord1 - 2across a 4-cycle lets Tom cover{0, 1, 2, 3}from1and force capture in2seconds!) - Even when capture is guaranteed, cycles can make it slower than
D. In Counterexample 2 above (tom = 3joined to0, 1; triangle0-1-2with ear4on0, 2and ear5on1, 2;jerry = 0), every vertex is within distance2of Tom (D = 2). Yet in Second 1 Jerry flees0 -> 2; no matter where Tom moves (3,0, or1), Jerry has a safe vertex in Second 2 (2,5, or4) out of Tom's 1-step reach, stretching optimal capture to3seconds.
When would the BFS shortcut be valid?
- Graph restriction — Trees and forests: On a tree there is a unique simple path between any two vertices, so Jerry can never slip around Tom. Every step Tom takes toward Jerry permanently shrinks Jerry's reachable subtree, making
Dexact (after returning-1ifd_tom(jerry)is unreachable). - Changed objective — Pure non-reactive race: If the question only asked "What is the farthest vertex from Tom that Jerry can reach strictly before Tom if neither turns back?", comparing
d_jerry(v) < d_tom(v)answers that static race directly. Adversarial pursuit with turns and cycles requires game-state analysis.
- Chordless cycles of length
Model each position with whose turn is next
Because optimal play depends on both players' locations and who moves next, a game state is
(turn, t, j)witht != j. Using minimax—where the maximizing player picks the largest outcome and the minimizing player picks the smallest—the exact equations are:jerry_time[t][j] = guaranteed seconds left at start of a second (Jerry moves next) = max over j_next in moves[j] (with j_next != t) of tom_time[t][j_next] tom_time[t][j] = guaranteed seconds left mid-second (Tom moves next, counting this second) = 1 if adjacent[t][j] is True = 1 + min over t_next in moves[t] of jerry_time[t_next][j] otherwiseNotice how directly this reflects the problem's guarantee: Tom only needs one move
t_nextthat traps Jerry quickly (min), whereas that guarantee must hold against every legal escapej_nextJerry might try (max). Withn <= 50, each table hasn * (n - 1) <= 2,450non-capture pairs—at most4,900total states.Key idea: work backward from captures with retrograde BFS
Why can we not solve these equations with top-down recursion + memoization (DFS)? Because both players can stay in place, the state graph is full of cycles:
(t, j)transitions to(t, j)! Even on Example 1's 5-vertex tree where Tom wins in3seconds, naive DFS loops back to states currently on the call stack, so "visiting a cycle in DFS" does not mean Jerry escapes.Instead, we use retrograde analysis—starting from the end states whose capture times we already know (
1second) and propagating backward like BFS:Known end states Jerry-turn parent (MAX) Tom-turn parent (MIN) ---------------- ----------------------- --------------------- tom_time[t][j] = 1 ---> Decrement escapes_left[t][j_prev]. ---> First settled child (t, j) (for all adjacent t, j) Settle jerry_time ONLY when IMMEDIATELY settles escapes_left hits 0! tom_time[t_prev][j] = time + 1!Why does a plain FIFO queue settle states in non-decreasing capture time without needing Dijkstra's priority queue? Look at the alternating turn layers:
- Queue starts with only
"tom"states of time1(Layer 1). - Popping
"tom"states of time1can only enqueue"jerry"states of time1(Layer 2). - Popping
"jerry"states of time1can only enqueue"tom"states of time2(Layer 3). - Popping
"tom"states of time2can only enqueue"jerry"states of time2(Layer 4), and so on.
Every queue push moves strictly from Layer
Lto LayerL + 1, so capture times popped from the front are guaranteed to be1, 1, ..., 2, 2, ..., 3, 3, ...in non-decreasing order! Consequently:- For a Tom state (
min), the first child(t, j)popped from the queue has the smallest possiblejerry_time, settlingtom_time[t_prev][j] = current_time + 1immediately. - For a Jerry state (
max), we count how many safe escapes remain unknown (escapes_left). If all escapes eventually get settled, the last one popped has the largesttom_time, settlingjerry_time. If any escape never settles,escapes_leftnever hits0, leavingjerry_timeasUNKNOWN(-1)—meaning Jerry always has an unsettled escape to step into forever!
- Queue starts with only
Build the move lists, tables, and escape counters
Let's write the graph helpers and state initialization cleanly. Because staying in place is legal every turn,
moves[v]starts with[v]and appendsv's neighbors:from typing import List from collections import deque # Sentinel value for game states where Tom cannot yet guarantee a finite capture time UNKNOWN = -1 def build_moves(n: int, edges: List[List[int]]) -> List[List[int]]: """Return moves[v]: [v, neighbor_1, ...] listing all vertices reachable in one turn (stay or step).""" moves = [[v] for v in range(n)] for a, b in edges: moves[a].append(b) moves[b].append(a) return moves def build_adjacent(n: int, edges: List[List[int]]) -> List[List[bool]]: """Return an n x n boolean matrix where adjacent[a][b] is True iff edge (a, b) exists.""" adjacent = [[False] * n for _ in range(n)] for a, b in edges: adjacent[a][b] = True adjacent[b][a] = True return adjacentInside
guaranteed_capture_time, we buildjerry_time,tom_time, andescapes_left, then seedqueuewith every adjacent("tom", t, j)state at time1:def init_retrograde_tables(n: int, moves: List[List[int]], adjacent: List[List[bool]]): jerry_time = [[UNKNOWN] * n for _ in range(n)] tom_time = [[UNKNOWN] * n for _ in range(n)] escapes_left = [[0] * n for _ in range(n)] for t in range(n): for j in range(n): if j == t: continue for j_next in moves[j]: if j_next != t: escapes_left[t][j] += 1 queue = deque() for t in range(n): for j in range(n): if adjacent[t][j]: tom_time[t][j] = 1 queue.append(("tom", t, j)) return jerry_time, tom_time, escapes_left, queuePropagate backward through the queue
Because the graph is undirected and
moves[v]containsvitself,j_prevcould move tojif and only ifj_prev in moves[j](and similarlyt_prev in moves[t]). Checking!= UNKNOWNensures every state settles at most once:def run_backward_bfs(moves, jerry_time, tom_time, escapes_left, queue): while queue: turn, t, j = queue.popleft() if turn == "tom": current_time = tom_time[t][j] # Parent Jerry-turn states (t, j_prev) where Jerry stepped j_prev -> j for j_prev in moves[j]: if j_prev == t or jerry_time[t][j_prev] != UNKNOWN: continue escapes_left[t][j_prev] -= 1 if escapes_left[t][j_prev] == 0: jerry_time[t][j_prev] = current_time queue.append(("jerry", t, j_prev)) else: current_time = jerry_time[t][j] # Parent Tom-turn states (t_prev, j) where Tom stepped t_prev -> t for t_prev in moves[t]: if t_prev == j or tom_time[t_prev][j] != UNKNOWN: continue tom_time[t_prev][j] = current_time + 1 queue.append(("tom", t_prev, j))Trace Example 3 and Example 2 step by step
First trace Example 3: the 4-vertex diamond
[[0, 1], [0, 2], [1, 2], [1, 3], [2, 3]]withtom = 0, jerry = 3(moves = [[0, 1, 2], [1, 0, 2, 3], [2, 0, 1, 3], [3, 1, 2]]):Key initial escapes_left[t][j]: (0,3): 3 (stay 3, go 1, go 2) (1,3): 2 (stay 3, go 2; moving to 1 hits Tom) (2,3): 2 (stay 3, go 1; moving to 2 hits Tom) Layer 1 (Seed all 10 adjacent Tom states = 1; only (0,3) and (3,0) are non-adjacent): tom_time[0][1] = 1, tom_time[0][2] = 1, tom_time[1][0] = 1, tom_time[1][2] = 1, tom_time[1][3] = 1, tom_time[2][0] = 1, tom_time[2][1] = 1, tom_time[2][3] = 1, ... Pop Layer 1 -> Layer 2 (Jerry states = 1): Pop ("tom", 0, 1)=1, ("tom", 0, 2)=1 -> escapes_left[0][3]: 3 -> 2 -> 1 (staying on 3 still open!) Pop ("tom", 1, 2)=1, ("tom", 1, 3)=1 -> escapes_left[1][3]: 2 -> 1 -> 0 => jerry_time[1][3] = 1! Pop ("tom", 2, 1)=1, ("tom", 2, 3)=1 -> escapes_left[2][3]: 2 -> 1 -> 0 => jerry_time[2][3] = 1! Pop Layer 2 -> Layer 3 (Tom states = 2): Pop ("jerry", 1, 3)=1 -> Tom at 0 can step 0->1 => tom_time[0][3] = 1 + 1 = 2 Pop Layer 3 -> Layer 4 (Jerry states = 2): Pop ("tom", 0, 3)=2 -> escapes_left[0][3]: 1 -> 0 => jerry_time[0][3] = 2!Result:
jerry_time[0][3] = 2. Now compare Example 2 (stem0 - 1attached to 4-cycle1 - 2 - 3 - 4 - 1,tom = 0, jerry = 3):At leaf 0: jerry_time[1][0] = 1 DOES settle (if Jerry ever walked into dead-end 0 while Tom stood on 1). Around the 4-cycle {1, 2, 3, 4}, however, every pair (t, j) with j in {1, 2, 3, 4} keeps escapes_left >= 1: - Opposite cycle pair (1, 3) starts with escapes_left[1][3] = 3 (stay 3, go 2, go 4); popping ("tom", 1, 2)=1 and ("tom", 1, 4)=1 drops escapes_left[1][3] from 3 -> 2 -> 1 (stay 3 remains). - Adjacent cycle pair (1, 2) starts with escapes_left[1][2] = 2 (stay 2, go 3); popping ("tom", 1, 2)=1 drops escapes_left[1][2] from 2 -> 1 (escape to 3 remains). Queue empties without ever reaching jerry_time[0][3] -> returns -1.Complete solution
Putting the helpers and backward BFS together into
solution.py:from typing import List from collections import deque # Sentinel value for game states where Tom cannot yet guarantee a finite capture time UNKNOWN = -1 def build_moves(n: int, edges: List[List[int]]) -> List[List[int]]: """Return moves[v]: [v, neighbor_1, ...] listing all vertices reachable in one turn (stay or step).""" # Staying in place is always a legal turn, so start each vertex's move list with itself moves = [[v] for v in range(n)] for a, b in edges: moves[a].append(b) moves[b].append(a) return moves def build_adjacent(n: int, edges: List[List[int]]) -> List[List[bool]]: """Return an n x n boolean matrix where adjacent[a][b] is True iff edge (a, b) exists.""" adjacent = [[False] * n for _ in range(n)] for a, b in edges: adjacent[a][b] = True adjacent[b][a] = True return adjacent def guaranteed_capture_time(n: int, edges: List[List[int]], tom: int, jerry: int) -> int: """Return the minimum seconds for Tom to guarantee catching Jerry (Jerry moves first), or -1.""" # Equal starting positions mean capture at t = 0 before any turn is played if tom == jerry: return 0 moves = build_moves(n, edges) adjacent = build_adjacent(n, edges) # jerry_time[t][j]: guaranteed seconds left from the start of a second (Jerry moves next) # tom_time[t][j]: guaranteed seconds left mid-second after Jerry moved (Tom moves next), # counting the current second jerry_time = [[UNKNOWN] * n for _ in range(n)] tom_time = [[UNKNOWN] * n for _ in range(n)] # escapes_left[t][j]: count of Jerry's safe moves j_next (j_next != t) from (t, j) # whose resulting Tom-turn state (t, j_next) is still UNKNOWN. # Why skip j_next == t? Walking onto Tom ends the game in 1 second, which is never better # for Jerry than staying on j (staying reaches Tom's turn with at least 1 second left). escapes_left = [[0] * n for _ in range(n)] for t in range(n): for j in range(n): if j == t: continue for j_next in moves[j]: if j_next != t: escapes_left[t][j] += 1 # queue: FIFO queue of settled ("tom" | "jerry", tom_vertex, jerry_vertex) states. # Base case: if Tom is adjacent to Jerry on Tom's half-turn, Tom steps onto Jerry in 1 second. queue = deque() for t in range(n): for j in range(n): if adjacent[t][j]: tom_time[t][j] = 1 queue.append(("tom", t, j)) # Retrograde BFS: because phases strictly alternate tom(1) -> jerry(1) -> tom(2) -> jerry(2), # states leave the FIFO queue in non-decreasing order of guaranteed capture time. while queue: turn, t, j = queue.popleft() if turn == "tom": current_time = tom_time[t][j] # Find every start-of-second state (t, j_prev) from which Jerry could move to j for j_prev in moves[j]: if j_prev == t or jerry_time[t][j_prev] != UNKNOWN: continue escapes_left[t][j_prev] -= 1 if escapes_left[t][j_prev] == 0: # All of Jerry's escape options are now finite; the last settled one is the max jerry_time[t][j_prev] = current_time queue.append(("jerry", t, j_prev)) else: current_time = jerry_time[t][j] # Find every mid-second state (t_prev, j) from which Tom could move to t for t_prev in moves[t]: if t_prev == j or tom_time[t_prev][j] != UNKNOWN: continue # Tom minimizes: the first settled child popped from the queue gives the smallest time tom_time[t_prev][j] = current_time + 1 queue.append(("tom", t_prev, j)) # Any state still UNKNOWN has at least one cycle of unending escapes for Jerry answer = jerry_time[tom][jerry] if answer == UNKNOWN: return -1 return answer✅ Submit now — all tests should pass.
Intuition & how it works
Think of solving this pursuit game like solving a chess endgame tablebase backward from checkmate rather than trying to trace every possible move forward from the opening. Forward search gets tangled immediately because both Tom and Jerry are allowed to stand still or run in circles—so a game can loop forever on a cycle, or repeat positions even on a simple line graph where Tom eventually corners Jerry. Working backward—a technique called retrograde analysis—sidesteps loops completely: we list every position where Tom is standing right next to Jerry on Tom's turn (1 second to capture), and then ask which earlier positions are forced into those 1-second captures, then 2-second captures, and so on.
Two naive shortcuts fail here. Comparing shortest-path BFS (breadth-first search) distances from Tom and Jerry (max d_tom(v) over vertices v with d_jerry(v) < d_tom(v)) only works on trees; on Example 2 (stem 0 - 1 attached to 4-cycle 1 - 2 - 3 - 4 - 1, tom = 0, jerry = 3) it predicts 3 seconds when Jerry can actually dodge around the 4-cycle forever (-1), and on graphs with triangles and side pockets it undercounts finite capture times. Top-down recursive minimax (alternating min for Tom and max for Jerry) with DFS memoization also fails because staying in place creates state-graph cycles even on winning trees.
Walk through Example 3—the 4-vertex diamond [[0, 1], [0, 2], [1, 2], [1, 3], [2, 3]] (tom = 0, jerry = 3)—to see retrograde BFS work in four tiny waves:
- Seed 1-second Tom wins: Every adjacent pair
(t, j)getstom_time[t][j] = 1—all 10 ordered pairs except(0, 3)and(3, 0)! In particular, hub1is adjacent to0,2, and3, sotom_time[1][2] = 1andtom_time[1][3] = 1are both seeded immediately. - Close all escapes for cornered Jerry states (
time = 1): When Tom stands on1and Jerry stands on3, Jerry's2non-suicidal moves (3 -> 3and3 -> 2) both land intom_time = 1states, reducingescapes_left[1][3]from2 -> 0and settlingjerry_time[1][3] = 1. (At(0, 3), by contrast,0 -> 1and0 -> 2close 2 of Jerry's 3 options, leaving staying on3unsettled!) - Advance Tom's best move (
time = 2): Becausejerry_time[1][3] = 1is now settled, Tom standing at0on Tom's half-turn can step0 -> 1to guaranteetom_time[0][3] = 1 + 1 = 2. - Seal the starting state (
time = 2): Now Jerry's last remaining option from(0, 3)—staying on3intotom_time[0][3] = 2—is also settled! With0escapes left,jerry_time[0][3]takes the final (largest) escape time,2.
Complexity
- Time:
O(n * (n + m)), wherenis the number of vertices andmis the number of undirected edges. There are at most2 * n * (n - 1)non-capture states ("tom"and"jerry"phases across pairs(t, j)), and each state enters and leaves the FIFO queue at most once because of the!= UNKNOWNguard. When"tom"state(t, j)pops, we loop overmoves[j](deg(j) + 1neighbors); summed across allnchoices oft, that performsn * sum(deg(j) + 1) = n * (n + 2m)operations, and"jerry"pops plusescapes_leftinitialization do the exact same amount of work. Atn = 50andm <= 1,225, total work is well under400,000simple loop steps. - Space:
O(n^2 + m), becausejerry_time,tom_time,escapes_left,adjacent, andqueueeach store at mostO(n^2)entries (2,500cells per50 x 50table), whilemovesstoresn + 2mvertex IDs.
Edge cases
- Identical starting vertices (
tom == jerry): Caught at time0before Jerry's first move; handled immediately at the top of the function (includingn = 1, edges = []). - Disconnected components or isolated vertices (
n = 2, edges = []):adjacentis allFalse, the queue starts empty, andjerry_time[tom][jerry]staysUNKNOWN, returning-1. - Adjacent starts where Jerry escapes first (Example 1:
0 - 1 - 2branching to3, 4withtom = 0, jerry = 1): Returns3, not1, because Jerry moves first each second and retreats1 -> 2 -> 3ahead of Tom. Adjacent start returns1only when every neighbor of Jerry (and Jerry's current vertex) is already adjacent to Tom (e.g.,tomat the hub of a star or on a triangle0-1-2). - Chordless cycles of length
>= 4(Example 2:1 - 2 - 3 - 4 - 1): A chordless cycle is a ring of vertices with no shortcut edges across the middle; for everyt != jwhenjlies on a chordless cycle of length4or more, Jerry always has a cycle neighbor outside Tom's 1-step reach, soescapes_leftnever hits0and the function returns-1. - Finite capture slower than shortest-path distance: Graphs with triangles and degree-2 side pockets (tested in
tests.py) take3seconds even though every vertex is within BFS distance2of Tom.
Common mistakes
- Using the tree BFS distance formula
max { d_tom(v) : d_jerry(v) < d_tom(v) }on general graphs. That shortcut ignores cycles—returning finite numbers on 4-cycles where Jerry evades forever and undercounting capture time when Jerry dodges around triangles. - Running recursive DFS with a
visitingset. Because staying in place is legal,(t, j)always has a 2-step cycle back to(t, j). Treating a cycle on the DFS stack as-1falsely declares infinite evasion on almost every graph, including a 3-vertex path. - Omitting whose turn is next from the state. Position
(0, 1)on path0 - 1 - 2takes2seconds when Jerry moves next (jerry_time[0][1] = 2), versus1second when Tom moves next (tom_time[0][1] = 1). - Settling a Jerry state on the first settled child instead of waiting for
escapes_left == 0. Tom needs just one winning move (min), whereas Jerry maximizes (max) and only gets caught once every escape route is proven finite. - Counting
j_next == t(Jerry walking onto Tom) insideescapes_left. Sincetom_time[t][t]is never queued as an(adjacent)distinct pair, countingj_next == tleavesescapes_leftpermanently stuck at1whenever Tom stands next to Jerry, breaking convergence! - Forgetting to include staying (
vinsidemoves[v]). Without staying, Jerry would be forced to leave a safe leaf right into Tom's arms, or players on bipartite graphs would pass each other forever due to parity.
Alternative approaches
- Synchronous value iteration (Bellman updates): Store
val[t][j]initialized to+infinity(0ont == j) and repeatedly recomputemaxover Jerry's moves ofminover Tom's moves (1 + val[t_next][j_next]) across alln^2pairs until a full pass makes zero changes. Afterkrounds it finds all capture times<= k(taking at mostn^2rounds), which is super compact fortests.pycross-checking, though slower (O(n^2 * (n + m)^2 / n)worst-case) thanO(n * (n + m))retrograde BFS. - Tree-only BFS race shortcut (
O(n + m)): If the input graph were guaranteed to be a tree, two BFS passes fromtomandjerrycomputingmax { d_tom(v) : d_jerry(v) < d_tom(v) }solve the game in linear time without building ann x nstate table.
Follow-up questions
- How does the solution change if Tom takes the first half-turn of every second instead of Jerry? Almost nothing in the retrograde engine changes! A game where Tom moves first at the start of Second 1 begins directly in our mid-second state
("tom", tom, jerry)(whiletom == jerrystill returns0), so you run the exact same backward BFS and returntom_time[tom][jerry]instead ofjerry_time[tom][jerry](-1ifUNKNOWN). On Example 1 (tom = 0, jerry = 1),tom_time[0][1]immediately returns1instead of3because Tom steps onto1before Jerry can flee. - How would you extend the state tables to output Tom's optimal next vertex—or an unending escape move for Jerry when capture is impossible? Store two policy tables alongside the time tables: whenever
("jerry", t, j)settlestom_time[t_prev][j] = current_time + 1, recordbest_tom_move[t_prev][j] = t; whenever the final escapejbringsescapes_left[t][j_prev]down to0, recordbest_jerry_move[t][j_prev] = j. When the answer is-1, any Jerry state withjerry_time == UNKNOWNstill hasescapes_left > 0, so Jerry can evade forever simply by choosing any movej_next != twhosetom_time[t][j_next]remainsUNKNOWN. - What happens to the state space and complexity if two pursuers cooperate on each turn to trap a single evader? Replace
twith the pair(t1, t2)so states become(turn, t1, t2, j)—roughly2 * n^3states (250,000states atn = 50, or125,000exploitingt1 <= t2symmetry). Both pursuers move during the pursuer phase, giving up to(deg(t1) + 1) * (deg(t2) + 1)transitions per state; retrograde BFS runs identically and confirms that two pursuers catch the evader on any connected cycle by pinching from opposite directions.
Follow-up questions
- How does the solution change if Tom takes the first half-turn of every second instead of Jerry?
- How would you extend the state tables to output Tom's optimal next vertex—or an unending escape move for Jerry when capture is impossible?
- What happens to the state space and complexity if two pursuers cooperate on each turn to trap a single evader?
Similar questions
- Maximum Independent Node Sum Across Trees
- Suited Runs and Same-Rank Card Groups
- Forest Root IDs and Root-to-Target Path
- Optimal Independent Node Sum on N-ary Trees
- In-Memory Key-Field Store with Record Expiry and Time Travel
- Conditional Form Evaluator with Numeric and Boolean Rules
More ZipHQ interview questions
- Maximum Independent Node Sum Across Trees Medium
- Conditional Form Evaluator with Numeric and Boolean Rules Medium
- Optimal Independent Node Sum on N-ary Trees Medium Pro
- In-Memory Key-Field Store with Record Expiry and Time Travel Hard Pro
- Debugging a Java LinkedHashMap LRU Cache Medium Pro
- Suited Runs and Same-Rank Card Groups Medium Pro
- Forest Root IDs and Root-to-Target Path Medium Pro
- Caching Repeated Approval Alerts with Safe Severity Updates Hard Pro