Leetcode #2038: Remove Colored Pieces if Both Neighbors are the Same Color
In this guide, we solve Leetcode #2038 Remove Colored Pieces if Both Neighbors are the Same Color in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Greedy, Math, String, Game Theory
Intuition
A locally optimal choice leads to a globally optimal result for this structure.
That means we can commit to decisions as we scan without backtracking.
Approach
Sort or preprocess if needed, then repeatedly take the best available local choice.
Maintain the minimal state necessary to validate the greedy decision.
Steps:
- Sort or preprocess as needed.
- Iterate and pick the best local option.
- Track the current solution.
Example
Input: colors = "AAABABB"
Output: true
Explanation:
AAABABB -> AABABB
Alice moves first.
She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.
Now it's Bob's turn.
Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.
Thus, Alice wins, so return true.
Python Solution
class Solution:
def winnerOfGame(self, colors: str) -> bool:
a = b = 0
for c, v in groupby(colors):
m = len(list(v)) - 2
if m > 0 and c == 'A':
a += m
elif m > 0 and c == 'B':
b += m
return a > b
Complexity
The time complexity is , where is the length of the string colors. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.