Remove Colored Pieces if Both Neighbors are the Same Color — LeetCode 2038 Python Solution

MediumGreedyMathStringGame Theory
Problem
#2038
Pattern
Greedy
Reading time
2 min

The 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.

Example

Input
colors = "AAABABB"
Output
true
Explanation
AAABABB -> AABABB

Python solution

Python
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

MeasureComplexity
TimeO(n), where n is the length of the string `colors`
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2038. Remove Colored Pieces if Both Neighbors are the Same Color is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2038. Remove Colored Pieces if Both Neighbors are the Same Color?
LeetCode 2038. Remove Colored Pieces if Both Neighbors are the Same Color is rated Medium on LeetCode.
What is the time complexity of LeetCode 2038. Remove Colored Pieces if Both Neighbors are the Same Color?
The Python solution on this page runs in O(n), where n is the length of the string `colors`.
What is the space complexity of LeetCode 2038. Remove Colored Pieces if Both Neighbors are the Same Color?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2038. Remove Colored Pieces if Both Neighbors are the Same Color cover?
LeetCode 2038. Remove Colored Pieces if Both Neighbors are the Same Color is tagged Greedy, Math, String and Game Theory on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview