Stone Game IV — LeetCode 1510 Python Solution

HardMathDynamic ProgrammingGame Theory
Problem
#1510
Reading time
3 min

The problem

Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile.

Example

Input
n = 1
Output
true
Explanation
Alice can remove 1 stone winning the game because Bob doesn't have any moves.

Python solution

Python
class Solution:
    def winnerSquareGame(self, n: int) -> bool:
        @cache
        def dfs(i: int) -> bool:
            if i == 0:
                return False
            j = 1
            while j * j <= i:
                if not dfs(i - j * j):
                    return True
                j += 1
            return False

        return dfs(n)

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1510. Stone Game IV is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1510. Stone Game IV?
LeetCode 1510. Stone Game IV is rated Hard on LeetCode.
What topics does LeetCode 1510. Stone Game IV cover?
LeetCode 1510. Stone Game IV is tagged Math, Dynamic Programming and Game Theory on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview