Stone Game IV Problem
Description
LeetCode Problem 1510.
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 <= 10^5
Solution
Approach: Dynamic Programming on Winning Positions
The game only depends on how many stones are left, not on who is moving or how we got there. So call a pile of i stones winning if the player about to move can force a win from it.
- A pile of
0stones is losing: the player to move has no move. - A pile of
istones is winning if there is some squarej * j <= isuch that the pilei - j * jis losing. Taking those stones hands the opponent a position they cannot win from. - If every move leads to a winning pile for the opponent, then
iis losing.
Every move makes the pile smaller, so we can fill a table win[0..n] from small to large and read off win[n]. For example win[1] = true (take 1), win[2] = false (the only move leaves 1), win[3] = true (leave 2), win[4] = true (take all 4).
We stop scanning squares as soon as one move wins. A top-down memoized recursion works too, but it would recurse about n levels deep (the move "take 1" chains n -> n-1 -> ...), which overflows the stack in some languages; the bottom-up table avoids that.
Complexity: O(n√n) time, since each pile tries at most √n squares, and O(n) space for the table.
class Solution:
def winnerSquareGame(self, n: int) -> bool:
# win[i]: the player to move with i stones left wins
win = [False] * (n + 1)
for i in range(1, n + 1):
j = 1
while j * j <= i:
if not win[i - j * j]: # this move leaves the opponent in a losing position
win[i] = True
break
j += 1
return win[n]