Game of Nim — LeetCode 1908 Python Solution
MediumLeetCode PremiumBit ManipulationBrainteaserArrayMathDynamic ProgrammingGame Theory
- Problem
- #1908
- Pattern
- Bit Manipulation
- Reading time
- 3 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(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.