Flip Game II Problem
Description
LeetCode Problem 294.
You are playing a Flip Game with your friend.
You are given a string currentState that contains only '+' and '-'. You and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move, and therefore the other person will be the winner.
Return true if the starting player can guarantee a win, and false otherwise.
Example 1:
Input: currentState = "++++"
Output: true
Explanation: The starting player can guarantee a win by flipping the middle "++" to become "+--+".
Example 2:
Input: currentState = "+"
Output: false
Constraints:
1 <= currentState.length <= 60currentState[i]is either'+'or'-'.- There cannot be more than 20 consecutive
'+'.
Follow up: Derive your algorithm's runtime complexity.
Solution
Approach: Sprague-Grundy Numbers
The direct solution is a game search: the current player wins if some move leaves a position where the opponent loses. With memoization on the whole string this works for short inputs, but the number of positions grows quickly when the string has several long runs of +.
The key observation is that a - never turns back into +. So the runs of consecutive + between the dashes are independent games: a move happens inside exactly one run. Game theory (the Sprague-Grundy theorem) says a sum of independent games is described by one number per game, its Grundy number, and the first player wins exactly when the XOR of those numbers is not zero.
The Grundy number of a single run depends only on its length L:
grundy[0] = grundy[1] = 0: no move is possible.- For
L >= 2, flipping the pair at positionsjandj + 1splits the run into two runs of lengthsjandL - 2 - j, whose value isgrundy[j] XOR grundy[L - 2 - j].grundy[L]is the mex of all these values: the smallest non-negative integer that does not appear.
Then split currentState at the dashes and XOR the Grundy numbers of the run lengths. For "++++", flipping the middle pair leaves two runs of length 1, worth 0, so grundy[4] is not 0 (it is 2) and the starting player wins. For "++-++", both runs have grundy[2] = 1 and 1 XOR 1 = 0, so the starting player loses: whatever they do in one run, the opponent copies it in the other.
Complexity: O(n2) time to compute the Grundy numbers up to n, and O(n) for the XOR. O(n) space.
class Solution:
def canWin(self, currentState: str) -> bool:
n = len(currentState)
# grundy[L]: the Grundy number of one run of L pluses, played on its own.
grundy = [0] * (n + 1)
for L in range(2, n + 1):
# Flipping the pair at j, j + 1 leaves two runs, of j and L - 2 - j pluses.
reachable = {grundy[j] ^ grundy[L - 2 - j] for j in range(L - 1)}
g = 0
while g in reachable: # mex: the smallest number not reachable
g += 1
grundy[L] = g
# The runs between '-' are independent games: XOR their Grundy numbers.
total = 0
for run in currentState.split("-"):
total ^= grundy[len(run)]
return total != 0