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:

  1. Jerry's move: Jerry either traverses one edge to an adjacent vertex or stays at his current vertex.
  2. 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 labeled 0 through n - 1.
  • edges contains 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

  1. Restate the turn order and clock rules

    We are given an undirected graph on n <= 50 vertices (0 through n - 1), Tom's starting vertex, and Jerry's starting vertex. Both players have full visibility of the graph and current positions. If tom == jerry initially, capture happens immediately at 0 seconds.

    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 s in which capture occurs. Tom chooses moves to minimize s; Jerry chooses moves to maximize s (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 - 2 branching to leaves 3 and 4 with tom = 0 and jerry = 1. Even though they start next to each other, in Second 1 Jerry retreats 1 -> 2 before Tom moves while Tom follows 0 -> 1; in Second 2 Jerry slips into leaf 3 (or 4) while Tom reaches 2; and Tom only corners Jerry in Second 3 (2 -> 3). So the answer is 3, not 1.
    • Jerry never benefits from walking onto Tom. Whenever t != j, Jerry is always allowed to stay on j, which survives Jerry's half-turn and forces Tom to take his half-turn in the same second s (giving capture time >= s, whereas walking onto Tom ends immediately in second s). Thus every optimal capture happens on Tom's half-turn.
  2. 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 from jerry (d_jerry), find every vertex v that 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, D is a valid lower bound: Jerry can walk a shortest path to that vertex v without ever being adjacent to Tom along the way, then sit on v until Tom walks d_tom(v) edges to reach it. However, D fails 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!
    
    1. Chordless cycles of length >= 4 allow infinite evasion (-1). In Example 2 (0 - 1 attached to 1 - 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 chord 1 - 2 across a 4-cycle lets Tom cover {0, 1, 2, 3} from 1 and force capture in 2 seconds!)
    2. Even when capture is guaranteed, cycles can make it slower than D. In Counterexample 2 above (tom = 3 joined to 0, 1; triangle 0-1-2 with ear 4 on 0, 2 and ear 5 on 1, 2; jerry = 0), every vertex is within distance 2 of Tom (D = 2). Yet in Second 1 Jerry flees 0 -> 2; no matter where Tom moves (3, 0, or 1), Jerry has a safe vertex in Second 2 (2, 5, or 4) out of Tom's 1-step reach, stretching optimal capture to 3 seconds.

    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 D exact (after returning -1 if d_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.
  3. 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) with t != 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]   otherwise
    

    Notice how directly this reflects the problem's guarantee: Tom only needs one move t_next that traps Jerry quickly (min), whereas that guarantee must hold against every legal escape j_next Jerry might try (max). With n <= 50, each table has n * (n - 1) <= 2,450 non-capture pairs—at most 4,900 total states.

  4. 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 in 3 seconds, 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 (1 second) 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:

    1. Queue starts with only "tom" states of time 1 (Layer 1).
    2. Popping "tom" states of time 1 can only enqueue "jerry" states of time 1 (Layer 2).
    3. Popping "jerry" states of time 1 can only enqueue "tom" states of time 2 (Layer 3).
    4. Popping "tom" states of time 2 can only enqueue "jerry" states of time 2 (Layer 4), and so on.

    Every queue push moves strictly from Layer L to Layer L + 1, so capture times popped from the front are guaranteed to be 1, 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 possible jerry_time, settling tom_time[t_prev][j] = current_time + 1 immediately.
    • 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 largest tom_time, settling jerry_time. If any escape never settles, escapes_left never hits 0, leaving jerry_time as UNKNOWN (-1)—meaning Jerry always has an unsettled escape to step into forever!
  5. 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 appends v'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 adjacent
    

    Inside guaranteed_capture_time, we build jerry_time, tom_time, and escapes_left, then seed queue with every adjacent ("tom", t, j) state at time 1:

    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, queue
    
  6. Propagate backward through the queue

    Because the graph is undirected and moves[v] contains v itself, j_prev could move to j if and only if j_prev in moves[j] (and similarly t_prev in moves[t]). Checking != UNKNOWN ensures 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))
    
  7. 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]] with tom = 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 (stem 0 - 1 attached to 4-cycle 1 - 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.
    
  8. 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:

  1. Seed 1-second Tom wins: Every adjacent pair (t, j) gets tom_time[t][j] = 1—all 10 ordered pairs except (0, 3) and (3, 0)! In particular, hub 1 is adjacent to 0, 2, and 3, so tom_time[1][2] = 1 and tom_time[1][3] = 1 are both seeded immediately.
  2. Close all escapes for cornered Jerry states (time = 1): When Tom stands on 1 and Jerry stands on 3, Jerry's 2 non-suicidal moves (3 -> 3 and 3 -> 2) both land in tom_time = 1 states, reducing escapes_left[1][3] from 2 -> 0 and settling jerry_time[1][3] = 1. (At (0, 3), by contrast, 0 -> 1 and 0 -> 2 close 2 of Jerry's 3 options, leaving staying on 3 unsettled!)
  3. Advance Tom's best move (time = 2): Because jerry_time[1][3] = 1 is now settled, Tom standing at 0 on Tom's half-turn can step 0 -> 1 to guarantee tom_time[0][3] = 1 + 1 = 2.
  4. Seal the starting state (time = 2): Now Jerry's last remaining option from (0, 3)—staying on 3 into tom_time[0][3] = 2—is also settled! With 0 escapes left, jerry_time[0][3] takes the final (largest) escape time, 2.

Complexity

  • Time: O(n * (n + m)), where n is the number of vertices and m is the number of undirected edges. There are at most 2 * 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 != UNKNOWN guard. When "tom" state (t, j) pops, we loop over moves[j] (deg(j) + 1 neighbors); summed across all n choices of t, that performs n * sum(deg(j) + 1) = n * (n + 2m) operations, and "jerry" pops plus escapes_left initialization do the exact same amount of work. At n = 50 and m <= 1,225, total work is well under 400,000 simple loop steps.
  • Space: O(n^2 + m), because jerry_time, tom_time, escapes_left, adjacent, and queue each store at most O(n^2) entries (2,500 cells per 50 x 50 table), while moves stores n + 2m vertex IDs.

Edge cases

  • Identical starting vertices (tom == jerry): Caught at time 0 before Jerry's first move; handled immediately at the top of the function (including n = 1, edges = []).
  • Disconnected components or isolated vertices (n = 2, edges = []): adjacent is all False, the queue starts empty, and jerry_time[tom][jerry] stays UNKNOWN, returning -1.
  • Adjacent starts where Jerry escapes first (Example 1: 0 - 1 - 2 branching to 3, 4 with tom = 0, jerry = 1): Returns 3, not 1, because Jerry moves first each second and retreats 1 -> 2 -> 3 ahead of Tom. Adjacent start returns 1 only when every neighbor of Jerry (and Jerry's current vertex) is already adjacent to Tom (e.g., tom at the hub of a star or on a triangle 0-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 every t != j when j lies on a chordless cycle of length 4 or more, Jerry always has a cycle neighbor outside Tom's 1-step reach, so escapes_left never hits 0 and the function returns -1.
  • Finite capture slower than shortest-path distance: Graphs with triangles and degree-2 side pockets (tested in tests.py) take 3 seconds even though every vertex is within BFS distance 2 of 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 visiting set. 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 -1 falsely declares infinite evasion on almost every graph, including a 3-vertex path.
  • Omitting whose turn is next from the state. Position (0, 1) on path 0 - 1 - 2 takes 2 seconds when Jerry moves next (jerry_time[0][1] = 2), versus 1 second 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) inside escapes_left. Since tom_time[t][t] is never queued as an (adjacent) distinct pair, counting j_next == t leaves escapes_left permanently stuck at 1 whenever Tom stands next to Jerry, breaking convergence!
  • Forgetting to include staying (v inside moves[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 (0 on t == j) and repeatedly recompute max over Jerry's moves of min over Tom's moves (1 + val[t_next][j_next]) across all n^2 pairs until a full pass makes zero changes. After k rounds it finds all capture times <= k (taking at most n^2 rounds), which is super compact for tests.py cross-checking, though slower (O(n^2 * (n + m)^2 / n) worst-case) than O(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 from tom and jerry computing max { d_tom(v) : d_jerry(v) < d_tom(v) } solve the game in linear time without building an n x n state 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) (while tom == jerry still returns 0), so you run the exact same backward BFS and return tom_time[tom][jerry] instead of jerry_time[tom][jerry] (-1 if UNKNOWN). On Example 1 (tom = 0, jerry = 1), tom_time[0][1] immediately returns 1 instead of 3 because Tom steps onto 1 before 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) settles tom_time[t_prev][j] = current_time + 1, record best_tom_move[t_prev][j] = t; whenever the final escape j brings escapes_left[t][j_prev] down to 0, record best_jerry_move[t][j_prev] = j. When the answer is -1, any Jerry state with jerry_time == UNKNOWN still has escapes_left > 0, so Jerry can evade forever simply by choosing any move j_next != t whose tom_time[t][j_next] remains UNKNOWN.
  • What happens to the state space and complexity if two pursuers cooperate on each turn to trap a single evader? Replace t with the pair (t1, t2) so states become (turn, t1, t2, j)—roughly 2 * n^3 states (250,000 states at n = 50, or 125,000 exploiting t1 <= t2 symmetry). 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

Similar questions

More ZipHQ interview questions

All 9 ZipHQ questions →