Similar Problems
Similar Problems not available
Remove Colored Pieces If Both Neighbors Are The Same Color - Leetcode Solution
Companies:
LeetCode: Remove Colored Pieces If Both Neighbors Are The Same Color Leetcode Solution
Difficulty: Medium
The problem "Remove Colored Pieces If Both Neighbors Are The Same Color" on LeetCode can be solved using a simple observation that whenever we remove a piece with the same color of its neighbors, the overall pattern remains the same, and we can continue removing such pieces until we cannot remove any more.
Here is the detailed solution with an explanation:
-
Traverse the string and identify pieces that have the same color as their neighbors.
-
Remove those pieces and update the string.
-
Repeat step 1 and 2 until we cannot remove any more pieces.
-
Check the remaining pieces and determine the winner.
Let's take an example to understand this better:
Example: Input: s = "AAABBC" Output: true
Explanation:
- We can remove "AAA" and update the string to "BBC".
- We can not remove any more pieces as no pieces have the same color as their neighbors.
- The remaining string is "BBC", and as there is only one color left, the winner is player A.
Solution:
We will use two pointers to traverse the string, i and j, and a flag to determine the current player.
-
Initialize i and j to 0.
-
While i < j, keep moving j until we find a piece that has a different color than s[i] or j reaches the end of the string.
-
If j has reached the end of the string, check if (j-i) >= 2, if yes, then we can remove the pieces, update the string, and return true as player A wins.
-
Otherwise, move i = j and reset j to i+1.
-
Repeat steps 2 to 4 until we cannot remove any more pieces.
-
If there is only one color left, return true as player A wins, otherwise return false as player B wins.
Here is the python code implementation of the above solution:
class Solution: def winnerOfGame(self, colors: str) -> bool: n = len(colors) i, j = 0, 1 flag_A = True count_A, count_B = 0, 0
while j < n:
while j < n and colors[j] == colors[i]:
j += 1
if j-i >= 3 and flag_A:
count_A += j-i-2
elif j-i >= 3 and not flag_A:
count_B += j-i-2
i = j
j = i+1
flag_A = not flag_A
if count_A > count_B:
return True
else:
return False
The time complexity of the above solution is O(n), where n is the length of the input string.
Remove Colored Pieces If Both Neighbors Are The Same Color Solution Code
1