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.
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally.
Example 1:
Input: n = 1 Output: true Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.
Example 2:
Input: n = 2 Output: false Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).
Example 3:
Input: n = 4 Output: true Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).
Constraints:
1 <= n <= 105Problem summary: Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she loses the game. Given a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math · Dynamic Programming
1
2
4
stone-game-v)stone-game-vi)stone-game-vii)stone-game-viii)stone-game-ix)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1510: Stone Game IV
class Solution {
private Boolean[] f;
public boolean winnerSquareGame(int n) {
f = new Boolean[n + 1];
return dfs(n);
}
private boolean dfs(int i) {
if (i <= 0) {
return false;
}
if (f[i] != null) {
return f[i];
}
for (int j = 1; j <= i / j; ++j) {
if (!dfs(i - j * j)) {
return f[i] = true;
}
}
return f[i] = false;
}
}
// Accepted solution for LeetCode #1510: Stone Game IV
func winnerSquareGame(n int) bool {
f := make([]int, n+1)
var dfs func(int) bool
dfs = func(i int) bool {
if i <= 0 {
return false
}
if f[i] != 0 {
return f[i] == 1
}
for j := 1; j <= i/j; j++ {
if !dfs(i - j*j) {
f[i] = 1
return true
}
}
f[i] = -1
return false
}
return dfs(n)
}
# Accepted solution for LeetCode #1510: Stone Game IV
class Solution:
def winnerSquareGame(self, n: int) -> bool:
@cache
def dfs(i: int) -> bool:
if i == 0:
return False
j = 1
while j * j <= i:
if not dfs(i - j * j):
return True
j += 1
return False
return dfs(n)
// Accepted solution for LeetCode #1510: Stone Game IV
struct Solution;
use std::collections::HashMap;
impl Solution {
fn winner_square_game(n: i32) -> bool {
let mut memo: HashMap<i32, bool> = HashMap::new();
Self::dp(n, &mut memo)
}
fn dp(n: i32, memo: &mut HashMap<i32, bool>) -> bool {
if let Some(&res) = memo.get(&n) {
return res;
}
let x = Self::sqrt(n);
let res = if x * x == n {
true
} else {
let mut res = false;
for i in 1..=x {
let y = n - i * i;
if !Self::dp(y, memo) {
res = true;
break;
}
}
res
};
memo.insert(n, res);
res
}
fn sqrt(x: i32) -> i32 {
(x as f64).sqrt() as i32
}
}
#[test]
fn test() {
let n = 1;
let res = true;
assert_eq!(Solution::winner_square_game(n), res);
let n = 2;
let res = false;
assert_eq!(Solution::winner_square_game(n), res);
let n = 4;
let res = true;
assert_eq!(Solution::winner_square_game(n), res);
let n = 7;
let res = false;
assert_eq!(Solution::winner_square_game(n), res);
let n = 17;
let res = false;
assert_eq!(Solution::winner_square_game(n), res);
}
// Accepted solution for LeetCode #1510: Stone Game IV
function winnerSquareGame(n: number): boolean {
const f: number[] = new Array(n + 1).fill(0);
const dfs = (i: number): boolean => {
if (i <= 0) {
return false;
}
if (f[i] !== 0) {
return f[i] === 1;
}
for (let j = 1; j * j <= i; ++j) {
if (!dfs(i - j * j)) {
f[i] = 1;
return true;
}
}
f[i] = -1;
return false;
};
return dfs(n);
}
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.