MediumNo. 2038

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

Pattern
Greedy
Topics
Greedy, Math, String, Game Theory
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

PythonSolution
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

Time
O(n)where n is the length of the string `colors`
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
1927Sum GameMedium
2029Stone Game IXMedium
1247Minimum Swaps to Make Strings EqualMedium
1561Maximum Number of Coins You Can GetMedium
1686Stone Game VIMedium
1903Largest Odd Number in StringEasy

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.

Free to download. Check it runs on your machine, then pick a plan.