Magicsheet logo

Remove Colored Pieces if Both Neighbors are the Same Color

Medium
89.1%
Updated 6/1/2025

Remove Colored Pieces if Both Neighbors are the Same Color

What is this problem about?

The Remove Colored Pieces if Both Neighbors are the Same Color interview question is a two-player game theory problem. Alice and Bob alternate turns on a string of colored pieces (each piece is either 'A' or 'B'). Alice can only remove an 'A' piece if both its immediate neighbors are also 'A'. Bob can only remove a 'B' piece if both its immediate neighbors are also 'B'. The player who cannot make a move loses. You must determine if Alice wins assuming both play optimally.

Why is this asked in interviews?

This problem is asked at companies like J.P. Morgan, Yelp, MathWorks, Roblox, and IBM because it tests a candidate's ability to recognize when a seemingly complex game theory problem reduces to a simple counting argument. It rewards mathematical insight over brute-force simulation. Recognizing independence between Alice's and Bob's moves is the key insight that unlocks an O(n) solution.

Algorithmic pattern used

The pattern is greedy counting with game theory observation. The crucial insight is that Alice's moves and Bob's moves are completely independent — removing an 'A' piece never affects Bob's available moves and vice versa. Therefore, the game outcome depends only on whether Alice has strictly more valid moves than Bob. Count the number of 'AAA' triplets (giving Alice a valid move) and 'BBB' triplets (giving Bob a valid move). Alice wins if her count exceeds Bob's count.

Example explanation

Consider the string "AAABABB". Alice can remove the middle 'A' in "AAA" — there is exactly one such opportunity. Bob can look for "BBB" — scanning through "BABB", there is no "BBB" substring, so Bob has 0 moves. Alice's count (1) > Bob's count (0), so Alice wins.

Now consider "AABABB". Alice has 0 valid moves (no "AAA"), Bob also has 0. Since Alice moves first and can't move, Bob wins.

Common mistakes candidates make

  • Simulating the game turn by turn, which is unnecessarily complex and prone to bugs.
  • Forgetting that pieces shift after removal — but in this problem, because moves are independent, you can simply count up front.
  • Confusing ">=" with ">": Alice wins only if she has strictly more moves than Bob, not equal.
  • Searching for substrings of length 3 incorrectly and double-counting overlapping runs.

Interview preparation tip

For the Remove Colored Pieces if Both Neighbors are the Same Color coding problem, practice identifying game theory problems where the two players' action spaces are disjoint. Once you realize Alice and Bob can never interfere with each other, the greedy counting pattern immediately follows. In your interview, explain this independence observation out loud before writing any code — it demonstrates deep problem analysis and will impress interviewers at firms like Roblox and IBM.

Similar Questions