Skip to content

2038. Remove Colored Pieces if Both Neighbors are the Same Color

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.

Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first.

  • Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A'. She is not allowed to remove pieces that are colored 'B'.
  • Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B'. He is not allowed to remove pieces that are colored 'A'.
  • Alice and Bob cannot remove pieces from the edge of the line.
  • If a player cannot make a move on their turn, that player loses and the other player wins.

Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins.

Example 1:

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.

Example 2:

Input: colors = “AA”
Output: false
Explanation:
Alice has her turn first.
There are only two ‘A’s and both are on the edge of the line, so she cannot move on her turn.
Thus, Bob wins, so return false.

Example 3:

Input: colors = “ABBBBBBBAAA”
Output: false
Explanation:
ABBBBBBBAAA -> ABBBBBBBAA
Alice moves first.
Her only option is to remove the second to last ‘A’ from the right.

ABBBBBBBAA -> ABBBBBBAA
Next is Bob’s turn.
He has many options for which ‘B’ piece to remove. He can pick any.

On Alice’s second turn, she has no more pieces that she can remove.
Thus, Bob wins, so return false.

Constraints:

  • 1 <= colors.length <= 10**5
  • colors consists of only the letters 'A' and 'B'

Solve

White board

  • Quickly remove edge case:
    • Length less than 2 then no game is play here, Alice loss in the spot
  • The best move Alice can play isn’t affect B at all
    • Alice can’t touch color B, Bob also can’t touch color A
    • This mean I can do some count and try to know how much move can Alice and Bob make from a stage or just simulating the game with random move until I know who won

Let start with Counting and see how can we done this:

  • With a continuous range with same color length any we can remove at most length(range)-2. For example: “BBBB” -> “BBB” -> “BB”
  • We can count all base on all possible continuous range we can find going in one loop from left to right

Implementation

Counting

I just start spamming keyboard for code and here is the first implementation

ALICE_WINS = True
ALICE_LOSE = False

class Solution:
    def winnerOfGame(self, colors: str) -> bool:
        if len(colors) <= 2:
            return ALICE_LOSE

        countA, countB = 0, 0
        start = 0
        end = 0
        color = colors[0]
        for i,c in enumerate(colors):
            if i == 0:
                continue
            if c == color:
                end += 1
                continue
            if color == 'A':
                countA += end - start - 1
            else:
                countB += end - start - 1
            start = end = i
            color = c
        if start != end:
            if color == 'A':
                countA += end - start - 1
            else:
                countB += end - start - 1

        return countA > countB

When we have total possible move of Alice equal to Bob’s, then Alice is lose because Alice go first, this mean only when countA > countB Alice can win

Debug process that throwing wrong answer because of I not handle case where length of range <= 2. This can be a lot of If case so I just adding max(0, end - start - 1) instead.

Also, separating the final start and end range outside the loop seen prone to error, so I padding a last character to colors so that the last loop always trigger

Final implementation.

Time Submitted Status Runtime Memory Language
10/02/2023 21:15 Accepted 197 ms 17.3 MB python3
ALICE_WINS = True
ALICE_LOSE = False

class Solution:
    def winnerOfGame(self, colors: str) -> bool:
        if len(colors) <= 2:
            return ALICE_LOSE

        countA, countB = 0, 0
        start = 0
        end = 0
        color = colors[0]
        for i,c in enumerate(colors + "C"):
            if i == 0:
                continue
            if c == color:
                end += 1
                continue
            if color == 'A':
                countA += max(0, end - start - 1)
            else:
                countB += max(0, end - start - 1)
            start = end = i
            color = c

        return countA > countB

This have time complexity of O(n)) and space complexity of O(1.

Unless we count colors + "C" cost us a O(n) space ??, remove it will return almost no different in python so I’m not sure

But here is the implementation without padding

Time Submitted Status Runtime Memory Language
10/02/2023 21:22 Accepted 186 ms 17.5 MB python3
ALICE_WINS = True
ALICE_LOSE = False

class Solution:
    def winnerOfGame(self, colors: str) -> bool:
        if len(colors) <= 2:
            return ALICE_LOSE

        countA, countB = 0, 0
        start = 0
        end = 0
        color = colors[0]
        for i,c in enumerate(colors):
            if i == 0:
                continue
            if c == color:
                end += 1
                continue
            if color == 'A':
                countA += max(0, end - start - 1)
            else:
                countB += max(0, end - start - 1)
            start = end = i
            color = c

        if start != end:
            if color == 'A':
                countA += max(0, end - start - 1)
            else:
                countB += max(0, end - start - 1)
        return countA > countB

Last update : October 13, 2023
Created : October 13, 2023