MediumNo. 0294LeetCode Premium

Flip Game II — LeetCode 294 Python Solution

Topics
Memoization, Math, Dynamic Programming, Backtracking, Game Theory
Reading time
3 min

The problem

You are playing a Flip Game with your friend. You are given a string currentState that contains only '+' and '-'.

Example

Input
currentState = "++++"
Output
true
Explanation
The starting player can guarantee a win by flipping the middle "++" to become "+--+".

Python solution

PythonSolution
class Solution:
    def canWin(self, currentState: str) -> bool:
        @cache
        def dfs(mask):
            for i in range(n - 1):
                if (mask & (1 << i)) == 0 or (mask & (1 << (i + 1)) == 0):
                    continue
                if dfs(mask ^ (1 << i) ^ (1 << (i + 1))):
                    continue
                return True
            return False

        mask, n = 0, len(currentState)
        for i, c in enumerate(currentState):
            if c == '+':
                mask |= 1 << i
        return dfs(mask)

Complexity

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

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 294. Flip Game II is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0464Can I WinMedium
0913Cat and MouseHard
1728Cat and Mouse IIHard
0070Climbing StairsEasy
0241Different Ways to Add ParenthesesMedium
0357Count Numbers with Unique DigitsMedium

Frequently asked questions

How hard is LeetCode 294. Flip Game II?

LeetCode 294. Flip Game II is rated Medium on LeetCode.

What topics does LeetCode 294. Flip Game II cover?

LeetCode 294. Flip Game II is tagged Memoization, Math, Dynamic Programming, Backtracking and Game Theory on LeetCode.

Is LeetCode 294. Flip Game II a premium problem?

Yes. LeetCode 294. Flip Game II 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.