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: false
💡 Note: Alice can remove 1² = 1 stone, leaving 1 stone for Bob. Bob removes 1² = 1 stone, leaving 0 for Alice. Alice cannot make a move and 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 - Dynamic Programming INPUT Initial Stone Pile 1 n = 1 stone n = 1 Input value Game Rules: - Alice moves first - Remove square number - No move = lose - Squares: 1,4,9,16... ALGORITHM STEPS 1 Initialize DP Array dp[i] = can current win? 2 Base Case: dp[0]=false 0 stones = lose 3 Check All Squares Try removing 1,4,9... 4 Win Condition dp[i-k*k]=false ---> win DP Table (n=1) i=0 F i=1 T dp[1]=T (remove 1, opponent loses) FINAL RESULT ALICE WINS! Game Trace: 1. Alice: remove 1 stone 2. Bob: 0 stones left Bob cannot move! Output: true Alice wins optimally [OK] Verified Key Insight: For any state with n stones, the current player wins if they can remove k*k stones such that the remaining state (n - k*k) is a LOSING position for the opponent. dp[i] = true if any dp[i-k*k] = false. TutorialsPoint - Stone Game IV | Dynamic Programming Approach
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