Flip Game - Problem

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

You and your friend take turns to flip two consecutive "+" characters 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.

Input & Output

Example 1 — Single ++ Pair
$ Input: currentState = "+--++"
Output: ["+----"]
💡 Note: Only one ++ pair exists at positions 3-4, flipping it gives "+----"
Example 2 — Multiple ++ Pairs
$ Input: currentState = "++--++"
Output: ["----++", "++----"]
💡 Note: Two ++ pairs: positions 0-1 and 4-5. Flipping first gives "----++", flipping second gives "++----"
Example 3 — No Valid Moves
$ Input: currentState = "+-+-"
Output: []
💡 Note: No consecutive ++ pairs exist, so no valid moves possible

Constraints

  • 1 ≤ currentState.length ≤ 500
  • currentState[i] is either '+' or '-'

Visualization

Tap to expand
Flip Game - Optimal Solution INPUT currentState string: + i=0 - i=1 - i=2 + i=3 + i=4 = Plus (+) = Minus (-) Goal: Find consecutive "++" and flip to "--" Return all possible states Input: "+--++" ALGORITHM STEPS 1 Iterate through string Loop i from 0 to len-2 2 Check for "++" If s[i]=="+" AND s[i+1]=="+" 3 Create new state Replace "++" with "--" 4 Add to result Store in result array Scanning Process: i=0: "+-" -- No match i=1: "--" -- No match i=2: "-+" -- No match i=3: "++" -- FOUND! Flip it! Result: "+----" FINAL RESULT After flipping at i=3: + - - - - FLIPPED Output Array: ["+----"] Status: OK 1 valid move found Time: O(n^2) Space: O(n) per result Key Insight: The optimal approach uses a single pass through the string, checking each consecutive pair of characters. When "++" is found at position i, create a new string by concatenating: s[0..i] + "--" + s[i+2..end]. Each valid flip generates one possible game state. String slicing takes O(n), making total time O(n^2). TutorialsPoint - Flip Game | Optimal Solution
Asked in
Google 15 Facebook 12
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen