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.

Input & Output

Example 1 — Basic Winning Case
$ Input: currentState = "++++"
Output: true
💡 Note: Player 1 can flip the first two ++ to get "--++", then no matter what player 2 does, player 1 can win on the next turn.
Example 2 — No Winning Move
$ Input: currentState = "+"
Output: false
💡 Note: Player 1 cannot make any move since there are no consecutive ++ pairs, so player 1 loses immediately.
Example 3 — Complex Case
$ Input: currentState = "++--++"
Output: true
💡 Note: Player 1 has two possible moves: flip first ++ or last ++. At least one of these moves leads to a winning strategy.

Constraints

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

Visualization

Tap to expand
Flip Game II - Game Theory Solution INPUT currentState String: + idx 0 + idx 1 + idx 2 + idx 3 Possible Flip Positions: Position 0-1: "++" at start Position 1-2: "++" middle Position 2-3: "++" at end input = "++++'" ALGORITHM STEPS 1 Find All "++" Pairs Scan string for consecutive + 2 Try Each Flip Flip "++" to "--" recursively 3 Check Opponent If opponent can't win, we win! 4 Backtrack Try all moves for best result Game Tree (partial): ++++ --++ +--+ ++-- ---- Opp Loses! FINAL RESULT Winning Strategy Found: Player 1 WINS! Winning Move Example: P1: ++++ --> --++ P2: --++ --> ---- P2 has no moves left! Output: true [OK] Player 1 guarantees win Key Insight: This is a minimax game theory problem. Player 1 wins if ANY move leads to a state where Player 2 CANNOT win. We use recursion with memoization to check all possible game states. Time: O(n!), Space: O(n!) for memoization. The key is: if opponent loses in ANY branch, we win! TutorialsPoint - Flip Game II | Optimal Solution (Minimax with Memoization)
Asked in
Google 15 Facebook 12 Microsoft 8 Amazon 6
32.0K Views
Medium Frequency
~25 min Avg. Time
890 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