Stone Game IV - Problem
Stone Game IV - A strategic battle of wits between two optimal players!
Alice and Bob are playing an exciting mathematical game with stones. There are
Rules:
• Alice goes first
• Players must remove at least 1 stone per turn
• Only perfect square numbers of stones can be removed
• The player who cannot make a move loses
• Both players play optimally
Goal: Determine if Alice can guarantee a win with optimal play.
Example: If there are 7 stones, Alice can remove 4 stones (2²), leaving 3 for Bob. Bob can only remove 1 stone, leaving 2 for Alice. Alice removes 1, Bob removes 1, and Alice wins!
Alice and Bob are playing an exciting mathematical game with stones. There are
n stones in a pile, and they take turns removing stones with a special twist - on each turn, a player can only remove a perfect square number of stones (1, 4, 9, 16, 25, ...).Rules:
• Alice goes first
• Players must remove at least 1 stone per turn
• Only perfect square numbers of stones can be removed
• The player who cannot make a move loses
• Both players play optimally
Goal: Determine if Alice can guarantee a win with optimal play.
Example: If there are 7 stones, Alice can remove 4 stones (2²), leaving 3 for Bob. Bob can only remove 1 stone, leaving 2 for Alice. Alice removes 1, Bob removes 1, and Alice wins!
Input & Output
example_1.py — Basic Case
$
Input:
n = 1
›
Output:
true
💡 Note:
Alice can remove 1 stone (1²) and Bob cannot make any move, so Alice wins.
example_2.py — Multiple Options
$
Input:
n = 7
›
Output:
false
💡 Note:
Alice can remove 1, 4 stones. If she removes 1, Bob faces 6 stones (Bob can win). If she removes 4, Bob faces 3 stones (Bob can win). No winning move for Alice.
example_3.py — Perfect Square
$
Input:
n = 17
›
Output:
false
💡 Note:
17 is not a winning position. No matter what Alice chooses (1, 4, 9, or 16), Bob will be in a winning position.
Visualization
Tap to expand
Understanding the Visualization
1
Understand the Rules
Players alternate removing perfect square numbers of stones (1, 4, 9, 16, ...)
2
Winning vs Losing Positions
A position is winning if you can make a move that puts opponent in losing position
3
Build Solution Bottom-Up
Use DP to determine winning/losing status for each number of stones
4
Check All Moves
For each position, try all valid perfect square moves
Key Takeaway
🎯 Key Insight: Use dynamic programming to build up winning/losing positions. A position is winning if any move leads to opponent losing!
Time & Space Complexity
Time Complexity
O(n√n)
For each of n positions, we check up to √n perfect squares
✓ Linear Growth
Space Complexity
O(n)
DP array to store results for each position from 0 to n
⚡ Linearithmic Space
Constraints
- 1 ≤ n ≤ 105
- Perfect squares only: Players can only remove 1², 2², 3², ... stones
- Both players play optimally
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code