MediumNo. 0464

Can I Win — LeetCode 464 Python Solution

Topics
Bit Manipulation, Memoization, Math, Dynamic Programming, Bitmask, Game Theory
Reading time
3 min

The problem

In the "100 game" two players take turns adding, to a running total, any integer from 1 to 10. The player who first causes the running total to reach or exceed 100 wins.

Example

Input
maxChoosableInteger = 10, desiredTotal = 11
Output
false
Explanation
No matter which integer the first player choose, the first player will lose.

Python solution

PythonSolution
class Solution:
    def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
        @cache
        def dfs(mask: int, s: int) -> bool:
            for i in range(1, maxChoosableInteger + 1):
                if mask >> i & 1 ^ 1:
                    if s + i >= desiredTotal or not dfs(mask | 1 << i, s + i):
                        return True
            return False

        if (1 + maxChoosableInteger) * maxChoosableInteger // 2 < desiredTotal:
            return False
        return dfs(0, 0)

Complexity

Time
O(2n)
Space · auxiliary
O(2n)

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 464. Can I Win is filed here because LeetCode tags it Bit Manipulation and Bitmask, 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
0638Shopping OffersMedium
0698Partition to K Equal Sum SubsetsMedium
0805Split Array With Same AverageHard
0913Cat and MouseHard
1659Maximize Grid HappinessHard
1728Cat and Mouse IIHard

Frequently asked questions

How hard is LeetCode 464. Can I Win?

LeetCode 464. Can I Win is rated Medium on LeetCode.

What is the time complexity of LeetCode 464. Can I Win?

The Python solution on this page runs in O(2n).

What is the space complexity of LeetCode 464. Can I Win?

The Python solution on this page uses O(2n) auxiliary space.

What topics does LeetCode 464. Can I Win cover?

LeetCode 464. Can I Win is tagged Bit Manipulation, Memoization, Math, Dynamic Programming, Bitmask 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.