Overflow in intermediate arithmetic
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.
The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0.
During each player's turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in graph[1].
Additionally, it is not allowed for the Cat to travel to the Hole (node 0).
Then, the game can end in three ways:
Given a graph, and assuming both players play optimally, return
1 if the mouse wins the game,2 if the cat wins the game, or0 if the game is a draw.Example 1:
Input: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]] Output: 0
Example 2:
Input: graph = [[1,3],[0],[3],[0,2]] Output: 1
Constraints:
3 <= graph.length <= 501 <= graph[i].length < graph.length0 <= graph[i][j] < graph.lengthgraph[i][j] != igraph[i] is unique.Problem summary: A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph. The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0. During each player's turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in graph[1]. Additionally, it is not allowed for the Cat to travel to the Hole (node 0). Then, the game can end in three ways: If ever the Cat occupies the same node as the Mouse, the Cat wins. If ever the Mouse reaches the Hole, the Mouse wins. If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw. Given a graph, and
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math · Dynamic Programming · Topological Sort
[[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
[[1,3],[0],[3],[0,2]]
cat-and-mouse-ii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #913: Cat and Mouse
class Solution {
private int n;
private int[][] g;
private int[][][] ans;
private int[][][] degree;
private static final int HOLE = 0, MOUSE_START = 1, CAT_START = 2;
private static final int MOUSE_TURN = 0, CAT_TURN = 1;
private static final int MOUSE_WIN = 1, CAT_WIN = 2, TIE = 0;
public int catMouseGame(int[][] graph) {
n = graph.length;
g = graph;
ans = new int[n][n][2];
degree = new int[n][n][2];
for (int i = 0; i < n; ++i) {
for (int j = 1; j < n; ++j) {
degree[i][j][MOUSE_TURN] = g[i].length;
degree[i][j][CAT_TURN] = g[j].length;
}
}
for (int i = 0; i < n; ++i) {
for (int j : g[HOLE]) {
--degree[i][j][CAT_TURN];
}
}
Deque<int[]> q = new ArrayDeque<>();
for (int j = 1; j < n; ++j) {
ans[0][j][MOUSE_TURN] = MOUSE_WIN;
ans[0][j][CAT_TURN] = MOUSE_WIN;
q.offer(new int[] {0, j, MOUSE_TURN});
q.offer(new int[] {0, j, CAT_TURN});
}
for (int i = 1; i < n; ++i) {
ans[i][i][MOUSE_TURN] = CAT_WIN;
ans[i][i][CAT_TURN] = CAT_WIN;
q.offer(new int[] {i, i, MOUSE_TURN});
q.offer(new int[] {i, i, CAT_TURN});
}
while (!q.isEmpty()) {
int[] state = q.poll();
int t = ans[state[0]][state[1]][state[2]];
List<int[]> prevStates = getPrevStates(state);
for (var prevState : prevStates) {
int pm = prevState[0], pc = prevState[1], pt = prevState[2];
if (ans[pm][pc][pt] == TIE) {
boolean win
= (t == MOUSE_WIN && pt == MOUSE_TURN) || (t == CAT_WIN && pt == CAT_TURN);
if (win) {
ans[pm][pc][pt] = t;
q.offer(prevState);
} else {
if (--degree[pm][pc][pt] == 0) {
ans[pm][pc][pt] = t;
q.offer(prevState);
}
}
}
}
}
return ans[MOUSE_START][CAT_START][MOUSE_TURN];
}
private List<int[]> getPrevStates(int[] state) {
List<int[]> pre = new ArrayList<>();
int m = state[0], c = state[1], t = state[2];
int pt = t ^ 1;
if (pt == CAT_TURN) {
for (int pc : g[c]) {
if (pc != HOLE) {
pre.add(new int[] {m, pc, pt});
}
}
} else {
for (int pm : g[m]) {
pre.add(new int[] {pm, c, pt});
}
}
return pre;
}
}
// Accepted solution for LeetCode #913: Cat and Mouse
const (
hole = 0
mouseStart = 1
catStart = 2
mouseTurn = 0
catTurn = 1
mouseWin = 1
catWin = 2
tie = 0
)
func catMouseGame(graph [][]int) int {
ans := [50][50][2]int{}
degree := [50][50][2]int{}
n := len(graph)
for i := 0; i < n; i++ {
for j := 1; j < n; j++ {
degree[i][j][mouseTurn] = len(graph[i])
degree[i][j][catTurn] = len(graph[j])
}
for _, j := range graph[hole] {
degree[i][j][catTurn]--
}
}
type tuple struct{ m, c, t int }
q := []tuple{}
for j := 1; j < n; j++ {
ans[0][j][mouseTurn], ans[0][j][catTurn] = mouseWin, mouseWin
q = append(q, tuple{0, j, mouseTurn})
q = append(q, tuple{0, j, catTurn})
}
for i := 1; i < n; i++ {
ans[i][i][mouseTurn], ans[i][i][catTurn] = catWin, catWin
q = append(q, tuple{i, i, mouseTurn})
q = append(q, tuple{i, i, catTurn})
}
getPrevStates := func(m, c, t int) []tuple {
pre := []tuple{}
pt := t ^ 1
if pt == catTurn {
for _, pc := range graph[c] {
if pc != hole {
pre = append(pre, tuple{m, pc, pt})
}
}
} else {
for _, pm := range graph[m] {
pre = append(pre, tuple{pm, c, pt})
}
}
return pre
}
for len(q) > 0 {
state := q[0]
m, c, t := state.m, state.c, state.t
q = q[1:]
x := ans[m][c][t]
for _, prevState := range getPrevStates(m, c, t) {
pm, pc, pt := prevState.m, prevState.c, prevState.t
if ans[pm][pc][pt] == tie {
win := (x == mouseWin && pt == mouseTurn) || (x == catWin && pt == catTurn)
if win {
ans[pm][pc][pt] = x
q = append(q, tuple{pm, pc, pt})
} else {
degree[pm][pc][pt]--
if degree[pm][pc][pt] == 0 {
ans[pm][pc][pt] = x
q = append(q, tuple{pm, pc, pt})
}
}
}
}
}
return ans[mouseStart][catStart][mouseTurn]
}
# Accepted solution for LeetCode #913: Cat and Mouse
HOLE, MOUSE_START, CAT_START = 0, 1, 2
MOUSE_TURN, CAT_TURN = 0, 1
MOUSE_WIN, CAT_WIN, TIE = 1, 2, 0
class Solution:
def catMouseGame(self, graph: List[List[int]]) -> int:
def get_prev_states(state):
m, c, t = state
pt = t ^ 1
pre = []
if pt == CAT_TURN:
for pc in graph[c]:
if pc != HOLE:
pre.append((m, pc, pt))
else:
for pm in graph[m]:
pre.append((pm, c, pt))
return pre
n = len(graph)
ans = [[[0, 0] for _ in range(n)] for _ in range(n)]
degree = [[[0, 0] for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(1, n):
degree[i][j][MOUSE_TURN] = len(graph[i])
degree[i][j][CAT_TURN] = len(graph[j])
for j in graph[HOLE]:
degree[i][j][CAT_TURN] -= 1
q = deque()
for j in range(1, n):
ans[0][j][MOUSE_TURN] = ans[0][j][CAT_TURN] = MOUSE_WIN
q.append((0, j, MOUSE_TURN))
q.append((0, j, CAT_TURN))
for i in range(1, n):
ans[i][i][MOUSE_TURN] = ans[i][i][CAT_TURN] = CAT_WIN
q.append((i, i, MOUSE_TURN))
q.append((i, i, CAT_TURN))
while q:
state = q.popleft()
t = ans[state[0]][state[1]][state[2]]
for prev_state in get_prev_states(state):
pm, pc, pt = prev_state
if ans[pm][pc][pt] == TIE:
win = (t == MOUSE_WIN and pt == MOUSE_TURN) or (
t == CAT_WIN and pt == CAT_TURN
)
if win:
ans[pm][pc][pt] = t
q.append(prev_state)
else:
degree[pm][pc][pt] -= 1
if degree[pm][pc][pt] == 0:
ans[pm][pc][pt] = t
q.append(prev_state)
return ans[MOUSE_START][CAT_START][MOUSE_TURN]
// Accepted solution for LeetCode #913: Cat and Mouse
/**
* [0913] Cat and Mouse
*
* A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.
* The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.
* The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0.
* During each player's turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in graph[1].
* Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
* Then, the game can end in three ways:
*
* If ever the Cat occupies the same node as the Mouse, the Cat wins.
* If ever the Mouse reaches the Hole, the Mouse wins.
* If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.
*
* Given a graph, and assuming both players play optimally, return
*
* 1 if the mouse wins the game,
* 2 if the cat wins the game, or
* 0 if the game is a draw.
*
*
* Example 1:
* <img alt="" src="https://assets.leetcode.com/uploads/2020/11/17/cat1.jpg" style="width: 300px; height: 300px;" />
* Input: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
* Output: 0
*
* Example 2:
* <img alt="" src="https://assets.leetcode.com/uploads/2020/11/17/cat2.jpg" style="width: 200px; height: 200px;" />
* Input: graph = [[1,3],[0],[3],[0,2]]
* Output: 1
*
*
* Constraints:
*
* 3 <= graph.length <= 50
* 1 <= graph[i].length < graph.length
* 0 <= graph[i][j] < graph.length
* graph[i][j] != i
* graph[i] is unique.
* The mouse and the cat can always move.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/cat-and-mouse/
// discuss: https://leetcode.com/problems/cat-and-mouse/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
// Credit: https://leetcode.com/problems/cat-and-mouse/solutions/746429/clean-rust-solution/
#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)]
enum Player {
Cat,
Mouse,
}
impl Player {
pub fn opposite(&self) -> Player {
match self {
Player::Cat => Player::Mouse,
Player::Mouse => Player::Cat,
}
}
}
#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)]
struct State {
turn: Player,
cat_pos: i32,
mouse_pos: i32,
}
impl State {
const WINNING_MOUSE_POS: i32 = 0;
pub fn new(turn: Player, cat_pos: i32, mouse_pos: i32) -> State {
State {
turn,
cat_pos,
mouse_pos,
}
}
pub fn winner(&self) -> Option<Player> {
if self.mouse_pos == State::WINNING_MOUSE_POS || self.cat_pos == State::WINNING_MOUSE_POS {
// If either the mouse or cat falls into the hole, the mouse wins.
Some(Player::Mouse)
} else if self.mouse_pos == self.cat_pos {
// If the cat catches the mouse, the cat wins.
Some(Player::Cat)
} else {
// Otherwise there isn't a winner yet.
None
}
}
}
impl Solution {
pub fn cat_mouse_game(graph: Vec<Vec<i32>>) -> i32 {
let mut graph_set: std::collections::HashMap<State, std::collections::HashSet<State>> =
std::collections::HashMap::new();
let mut rgraph: std::collections::HashMap<State, std::collections::HashSet<State>> =
std::collections::HashMap::new();
let mut states = std::collections::HashSet::new();
let mut state_winner: std::collections::HashMap<State, Player> =
std::collections::HashMap::new();
for (pos_one, pos_adjs) in graph.iter().enumerate() {
for pos_adj in pos_adjs {
for turn in &[Player::Mouse, Player::Cat] {
for cnst_pos in 0..graph.len() {
let (cat_pos, new_cat_pos, mouse_pos, new_mouse_pos) = match *turn {
Player::Cat => {
(pos_one as i32, *pos_adj, cnst_pos as i32, cnst_pos as i32)
}
Player::Mouse => {
(cnst_pos as i32, cnst_pos as i32, pos_one as i32, *pos_adj)
}
};
let from = State::new(*turn, cat_pos, mouse_pos);
let to = State::new(turn.opposite(), new_cat_pos, new_mouse_pos);
graph_set
.entry(from)
.or_insert(std::collections::HashSet::new())
.insert(to);
rgraph
.entry(to)
.or_insert(std::collections::HashSet::new())
.insert(from);
for state in vec![from, to] {
if let Some(winning_player) = state.winner() {
state_winner.insert(state, winning_player);
}
states.insert(state);
}
}
}
}
}
let mut degree_left = std::collections::HashMap::new();
let mut stack = Vec::new();
for state in states {
if let Some(adjs) = graph_set.get(&state) {
// The degree is the number of children left. Once all children are
// complete, the winner of this state can be determined
degree_left.insert(state, adjs.len() as i32);
} else {
degree_left.insert(state, 0);
}
if let Some(_) = state_winner.get(&state) {
degree_left.insert(state, 0);
}
if degree_left[&state] == 0 {
stack.push(state);
}
}
while let Some(state) = stack.pop() {
let winner = state_winner[&state];
for &parent in rgraph
.get(&state)
.unwrap_or(&std::collections::HashSet::new())
{
if state_winner.contains_key(&parent) {
continue;
}
// If it was the winner's turn last turn, then they can make the winning move.
if winner == parent.turn {
state_winner.insert(parent, winner);
stack.push(parent);
continue;
}
// Otherwise, decrease the `degree_left` count and if the degree is 0, this parent
// has no winning moves, and therefore we can set the winner.
// Safe unwrap as all states were put into `degree_left`.
*degree_left.get_mut(&parent).unwrap() -= 1;
if degree_left[&parent] == 0 {
state_winner.insert(parent, parent.turn.opposite());
stack.push(parent);
}
}
}
match state_winner.get(&State::new(Player::Mouse, 2, 1)) {
None => 0,
Some(Player::Mouse) => 1,
Some(Player::Cat) => 2,
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_0913_example_1() {
let graph = vec![
vec![2, 5],
vec![3],
vec![0, 4, 5],
vec![1, 4, 5],
vec![2, 3],
vec![0, 2, 3],
];
let result = 0;
assert_eq!(Solution::cat_mouse_game(graph), result);
}
#[test]
fn test_0913_example_2() {
let graph = vec![vec![1, 3], vec![0], vec![3], vec![0, 2]];
let result = 1;
assert_eq!(Solution::cat_mouse_game(graph), result);
}
}
// Accepted solution for LeetCode #913: Cat and Mouse
function catMouseGame(graph: number[][]): number {
const [HOLE, MOUSE_START, CAT_START] = [0, 1, 2];
const [MOUSE_TURN, CAT_TURN] = [0, 1];
const [MOUSE_WIN, CAT_WIN, TIE] = [1, 2, 0];
function get_prev_states(state: [number, number, number]): [number, number, number][] {
const [m, c, t] = state;
const pt = t ^ 1;
const pre = [] as [number, number, number][];
if (pt === CAT_TURN) {
for (const pc of graph[c]) {
if (pc !== HOLE) {
pre.push([m, pc, pt]);
}
}
} else {
for (const pm of graph[m]) {
pre.push([pm, c, pt]);
}
}
return pre;
}
const n = graph.length;
const ans: number[][][] = Array.from({ length: n }, () =>
Array.from({ length: n }, () => [TIE, TIE]),
);
const degree: number[][][] = Array.from({ length: n }, () =>
Array.from({ length: n }, () => [0, 0]),
);
for (let i = 0; i < n; i++) {
for (let j = 1; j < n; j++) {
degree[i][j][MOUSE_TURN] = graph[i].length;
degree[i][j][CAT_TURN] = graph[j].length;
}
for (const j of graph[HOLE]) {
degree[i][j][CAT_TURN] -= 1;
}
}
const q: [number, number, number][] = [];
for (let j = 1; j < n; j++) {
ans[0][j][MOUSE_TURN] = ans[0][j][CAT_TURN] = MOUSE_WIN;
q.push([0, j, MOUSE_TURN], [0, j, CAT_TURN]);
}
for (let i = 1; i < n; i++) {
ans[i][i][MOUSE_TURN] = ans[i][i][CAT_TURN] = CAT_WIN;
q.push([i, i, MOUSE_TURN], [i, i, CAT_TURN]);
}
while (q.length > 0) {
const state = q.shift()!;
const [m, c, t] = state;
const result = ans[m][c][t];
for (const prev_state of get_prev_states(state)) {
const [pm, pc, pt] = prev_state;
if (ans[pm][pc][pt] === TIE) {
const win =
(result === MOUSE_WIN && pt === MOUSE_TURN) ||
(result === CAT_WIN && pt === CAT_TURN);
if (win) {
ans[pm][pc][pt] = result;
q.push(prev_state);
} else {
degree[pm][pc][pt] -= 1;
if (degree[pm][pc][pt] === 0) {
ans[pm][pc][pt] = result;
q.push(prev_state);
}
}
}
}
}
return ans[MOUSE_START][CAT_START][MOUSE_TURN];
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.