Remove Colored Pieces if Both Neighbors are the Same Color - Problem
Colored Pieces Game
Alice and Bob are playing a strategic game with colored pieces arranged in a line. Each piece is colored either
Game Rules:
• Alice moves first and can only remove
• Bob can only remove
• A piece can only be removed if both its neighbors are the same color as the piece
• Edge pieces (first and last) can never be removed
• The first player who cannot make a move loses
Your Task: Determine if Alice wins when both players play optimally.
Example: In
Alice and Bob are playing a strategic game with colored pieces arranged in a line. Each piece is colored either
'A' (blue) or 'B' (red). The game follows these rules:Game Rules:
• Alice moves first and can only remove
'A' pieces• Bob can only remove
'B' pieces• A piece can only be removed if both its neighbors are the same color as the piece
• Edge pieces (first and last) can never be removed
• The first player who cannot make a move loses
Your Task: Determine if Alice wins when both players play optimally.
Example: In
"AAABBB", Alice can remove the middle 'A', and Bob can remove the middle 'B'. The game continues until one player runs out of valid moves. Input & Output
example_1.py — Python
$
Input:
colors = "AAABBB"
›
Output:
true
💡 Note:
Alice removes middle 'A' to get "AABBB", then Bob removes middle 'B' to get "AABB". No more moves possible. Alice made the last move, so she wins.
example_2.py — Python
$
Input:
colors = "AA"
›
Output:
false
💡 Note:
Alice cannot make any moves because there are no 'A' pieces with both neighbors being 'A'. Bob wins by default.
example_3.py — Python
$
Input:
colors = "ABBBBBBBAAA"
›
Output:
false
💡 Note:
Alice has 1 move from 'AAA' group (3-2=1). Bob has 5 moves from 'BBBBBB' group (6-2=4). Bob wins with more available moves.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Groups
Scan through the string and identify consecutive groups of same-colored pieces
2
Calculate Moves
For each group with 3+ pieces, the player gets (group_size - 2) possible moves
3
Compare Totals
Alice wins if her total available moves > Bob's total available moves
Key Takeaway
🎯 Key Insight: This game theory problem reduces to simple counting because move order doesn't affect the total number of available moves for each player.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the string to count consecutive groups
✓ Linear Growth
Space Complexity
O(1)
Only using a few variables to track counts and current group
✓ Linear Space
Constraints
- 1 ≤ colors.length ≤ 105
-
colors consists of only the letters
'A'and'B' - The string will always have at least one character
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code