Flip Game Problem
Description
LeetCode Problem 293.
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 all possible states of the string currentState after one valid move. You may return the answer in any order. If there is no valid move, return an empty list [].
Example 1:
Input: currentState = "++++"
Output: ["--++","+--+","++--"]
Example 2:
Input: currentState = "+"
Output: []
Constraints:
1 <= currentState.length <= 500currentState[i]is either'+'or'-'.
Solution
Approach: Try Every "++"
Each valid move flips one pair of adjacent + characters. So scan every index i from 0 to n - 2: whenever currentState[i] and currentState[i + 1] are both +, build the string with those two characters replaced by -- and add it to the result.
Pairs may overlap, which is fine: in "+++" both "--+" and "+--" are valid moves, and the scan finds both because it checks every starting index. If no ++ exists, the result is just empty (Example 2).
Complexity: O(n2) time, since there can be up to n - 1 moves and each builds a new string of length n. O(n2) space for the output.
class Solution:
def generatePossibleNextMoves(self, currentState: str) -> List[str]:
s = currentState
moves = []
for i in range(len(s) - 1):
if s[i] == "+" and s[i + 1] == "+":
moves.append(s[:i] + "--" + s[i + 2 :]) # flip this "++"
return moves