Leetcode 2038: Remove Colored Pieces if Both Neighbors are the Same Color

grid47
grid47
Exploring patterns and algorithms
Apr 17, 2024 5 min read

You are given a string colors consisting of two types of pieces, ‘X’ and ‘Y’, arranged in a line. Two players, Alex and Brian, play a game where they take turns removing pieces from the string. Alex moves first and can only remove a piece ‘X’ if both its neighbors are also ‘X’. Similarly, Brian can only remove a piece ‘Y’ if both its neighbors are also ‘Y’. Neither player can remove edge pieces. If a player cannot make a move, they lose. Determine whether Alex wins the game if both players play optimally.
Problem
Approach
Steps
Complexity
Input: The input is a single string `colors` of length `n`, where `colors[i]` is either 'X' or 'Y', representing the pieces.
Example: "XXYXXY"
Constraints:
• 1 <= colors.length <= 100000
• colors consists only of the characters 'X' and 'Y'
Output: Return `true` if Alex wins the game, or `false` if Brian wins the game.
Example: true
Constraints:
• The result must be computed efficiently due to the constraints on input size.
Goal: Determine the winner by counting the number of valid moves for each player and checking if Alex has more valid moves than Brian.
Steps:
• 1. Iterate through the string `colors`.
• 2. Count all segments of three consecutive 'X's (valid moves for Alex).
• 3. Count all segments of three consecutive 'Y's (valid moves for Brian).
• 4. Compare the counts: if Alex's count is greater than Brian's, return `true`; otherwise, return `false`.
Goal: The problem's constraints ensure that the input is manageable for efficient computation.
Steps:
• 1 <= colors.length <= 100000
• colors consists only of 'X' and 'Y'.
Assumptions:
• Players play optimally.
• The string always contains at least one 'X' or 'Y'.
Input: "XXYXYXX"
Explanation: Alex removes the middle 'X' from "XXYXYXX" to get "XYXYXX". Brian has no valid moves, so Alex wins. The function returns `true`.

Input: "YYXXYY"
Explanation: Neither Alex nor Brian has a valid move, so Brian wins because Alex cannot make the first move. The function returns `false`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus