HardNo. 1510

Stone Game IV — LeetCode 1510 Python Solution

Topics
Math, Dynamic Programming, Game Theory
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

PythonSolution
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

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

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

Related problems
No.ProblemDifficulty
0877Stone GameMedium
0375Guess Number Higher or Lower IIMedium
0464Can I WinMedium
0486Predict the WinnerMedium
0913Cat and MouseHard
1025Divisor GameEasy

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.

Free to download. Check it runs on your machine, then pick a plan.