#2038

Remove Colored Pieces if Both Neighbors are the Same Color

Medium
MathStringGreedyGame TheoryGreedyString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of simulating the game, we can count the maximum number of valid moves each player can make based on the initial configuration. This allows us to determine the winner without simulating each turn.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the number of valid moves Alice can make by iterating through the string and checking for 'AAA' patterns.
  2. 2Step 2: Count the number of valid moves Bob can make by checking for 'BBB' patterns.
  3. 3Step 3: Compare the counts: if Alice's moves are greater than Bob's, Alice wins; otherwise, Bob wins.
solution.py4 lines
1def winner(colors):
2    alice_moves = sum(1 for i in range(1, len(colors) - 1) if colors[i] == 'A' and colors[i - 1] == 'A' and colors[i + 1] == 'A')
3    bob_moves = sum(1 for i in range(1, len(colors) - 1) if colors[i] == 'B' and colors[i - 1] == 'B' and colors[i + 1] == 'B')
4    return alice_moves > bob_moves

Complexity note: The complexity is O(n) because we only need a single pass through the string to count the valid moves for both players.

  • 1The game is determined by the number of valid moves each player can make.
  • 2Players cannot remove pieces at the edges, which limits their options.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.