Stone Game IV - Problem
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.
Input & Output
Example 1 — Alice Wins
$
Input:
n = 1
›
Output:
true
💡 Note:
Alice can remove 1² = 1 stone, leaving 0 stones for Bob. Bob cannot make a move and loses.
Example 2 — Alice Loses
$
Input:
n = 2
›
Output:
true
💡 Note:
Alice can remove 1² = 1 stone, leaving 1 stone for Bob. Bob removes 1 stone and Alice loses.
Example 3 — Complex Case
$
Input:
n = 4
›
Output:
true
💡 Note:
Alice can remove 4 stones (2²=4), leaving 0 for Bob. Or remove 1 stone leaving 3 for Bob. Alice has winning moves.
Constraints
- 1 ≤ n ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Game Rules
Players alternate removing square numbers of stones (1, 4, 9, 16...)
2
Winning Strategy
Position is winning if any move leads to losing position for opponent
3
DP Solution
Build table of winning/losing positions from bottom up
Key Takeaway
🎯 Key Insight: A position is winning if you can make a move that puts your opponent in a losing position
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code