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
Stone Game IV: Alice vs BobAlice👩Bob👨Stone Pilen = 7Possible moves: Remove 1²=1, 2²=4, or 3²=9 stonesWinning positions1, 2, 4, 7, 8...Losing positions0, 3, 6...Game ends when no moves possible (0 stones left)Alice wins because position 7 is a winning position
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
Asked in
Google 15 Facebook 12 Amazon 8
28.0K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen