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.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Count removable pieces
To determine the winner, assuming both players play optimally:
- Count Removable Pieces:
- Alice can only remove pieces
A
that haveA
neighbours on both sides (i.e.,"AAA"
). - Bob can only remove pieces
B
that haveB
neighbours on both sides (i.e.,"BBB"
).
- Alice can only remove pieces
- Winning Condition:
- We count the number of such removable
A
s (let’s call thiscountA
) andB
s (countB
). - Alice goes first and can only remove
A
s, and Bob goes second and can only removeB
s. - If
countA > countB
, Alice will have more opportunities to remove pieces than Bob, leading to Alice winning. - If
countA <= countB
, Bob will either have equal or more opportunities, ensuring Bob wins or at least denies Alice her first move when the game ends.
- We count the number of such removable
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the stringcolors
, as we only need a single pass to countcountA
andcountB
. - 🧺 Space complexity:
O(1)
since no extra space proportional to input size is needed, just a few counters.