Game of Nim — LeetCode 1908 Python Solution

MediumLeetCode PremiumBit ManipulationBrainteaserArrayMathDynamic ProgrammingGame Theory
Problem
#1908
Reading time
3 min

The problem

Alice and Bob take turns playing a game with Alice starting first. In this game, there are n piles of stones.

Example

Input
piles = [1]
Output
true
Explanation
There is only one possible scenario:

Python solution

Python
class Solution:
    def nimGame(self, piles: List[int]) -> bool:
        @cache
        def dfs(st):
            lst = list(st)
            for i, x in enumerate(lst):
                for j in range(1, x + 1):
                    lst[i] -= j
                    if not dfs(tuple(lst)):
                        return True
                    lst[i] += j
            return False

        return dfs(tuple(piles))

Complexity

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

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1908. Game of Nim is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1908. Game of Nim?
LeetCode 1908. Game of Nim is rated Medium on LeetCode.
What topics does LeetCode 1908. Game of Nim cover?
LeetCode 1908. Game of Nim is tagged Bit Manipulation, Brainteaser, Array, Math, Dynamic Programming and Game Theory on LeetCode.
Is LeetCode 1908. Game of Nim a premium problem?
Yes. LeetCode 1908. Game of Nim is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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