Remove Colored Pieces if Both Neighbors are the Same Color - Problem

There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece.

Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first.

  • Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A'. She is not allowed to remove pieces that are colored 'B'.
  • Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B'. He is not allowed to remove pieces that are colored 'A'.
  • Alice and Bob cannot remove pieces from the edge of the line.
  • If a player cannot make a move on their turn, that player loses and the other player wins.

Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins.

Input & Output

Example 1 — Equal Groups
$ Input: colors = "AAABBBAA"
Output: false
💡 Note: Alice can remove 1 piece from AAA group, Bob can remove 1 piece from BBB group. Since they have equal moves and Alice goes first, Bob makes the last move and wins.
Example 2 — Alice Has More
$ Input: colors = "AA"
Output: false
💡 Note: No groups of 3+ consecutive pieces exist, so neither player can make any moves. Alice goes first but cannot move, so Bob wins immediately.
Example 3 — Large Alice Group
$ Input: colors = "ABBBBAA"
Output: false
💡 Note: Only the BBBB group has 4 pieces, giving Bob 2 moves (4-2=2). Alice has no groups of 3+, so Bob wins.

Constraints

  • 1 ≤ colors.length ≤ 105
  • colors[i] is either 'A' or 'B'

Visualization

Tap to expand
Remove Colored Pieces GameInput: AAABBBAAAAABBBAAGame Rules:• Alice removes A pieces with A neighbors• Bob removes B pieces with B neighbors• Cannot remove edge pieces• Player who cannot move losesAlice: 1 moveBob: 1 moveResult: false (Bob wins)
Understanding the Visualization
1
Input
String of A and B pieces arranged in a line
2
Process
Players alternate removing pieces when surrounded by same color
3
Output
True if Alice wins, false if Bob wins
Key Takeaway
🎯 Key Insight: Count total available moves for each player instead of simulating the game turn by turn
Asked in
Microsoft 12 Google 8
23.4K 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