MediumNo. 1908LeetCode Premium

Game of Nim — LeetCode 1908 Python Solution

Topics
Bit Manipulation, Brainteaser, Array, Math, Dynamic Programming, Game Theory
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

PythonSolution
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

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

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

Related problems
No.ProblemDifficulty
0464Can I WinMedium
0486Predict the WinnerMedium
0805Split Array With Same AverageHard
0877Stone GameMedium
1025Divisor GameEasy
1140Stone Game IIMedium

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.

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