Skip to main content
Back to problems
#2038
Medium Algorithms

Remove colored pieces if both neighbors are the same color

Math String Greedy Game Theory
63.1% acceptance
Feb 25, 2026
1636
127
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn winner_of_game(colors: String) -> bool {
    let chars: Vec<u8> = colors.bytes().collect();
    let n = chars.len();
    let mut alice = 0i32;
    let mut bob = 0i32;
    for i in 1..n.saturating_sub(1) {
      if chars[i] == b'A' && chars[i - 1] == b'A' && chars[i + 1] == b'A' {
        alice += 1;
      }
      if chars[i] == b'B' && chars[i - 1] == b'B' && chars[i + 1] == b'B' {
        bob += 1;
      }
    }
    alice > bob
  }
}