Remove Colored Pieces if Both Neighbors are the Same Color — LeetCode 2038 Python Solution
- Problem
- #2038
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
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
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 > bComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string `colors` |
| Space | O(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.