🎨Now live: Try our Free AI Image Generation Feature

Intuition
In this problem, we need to find groups of three contiguous tiles in a circular array where the middle tile is a different color than its left and right neighbors. This means we need to check each triplet of tiles in the array to see if they alternate in color.
Approach
- Initialization: Start by initializing a counter to keep track of the number of alternating groups.
- Iterate through the array: Loop through each tile in the array. Since the array is circular, we need to handle the wrapping around at the ends of the array.
- Check alternating condition: For each tile, check the colors of the current tile, the next tile, and the tile after that. Use modulo operation to wrap around the array.
- Update counter: If the colors alternate (i.e., the middle tile is different from the other two), increment the counter.
- Return result: After checking all possible triplets, return the counter.
Complexity
- Time complexity: O(n), where n is the number of tiles in the array. We are looping through the array once.
- Space complexity: O(1), since we are using a constant amount of extra space for variables.
Code
C++
class Solution {
public:
int numberOfAlternatingGroups(vector& colors) {
int res = 0;
int n = colors.size();
for (int i = 0; i < n; ++i) {
int pre = colors[i];
int cur = colors[(i + 1) % n];
int nxt = colors[(i + 2) % n];
if (pre != cur && cur != nxt) ++res;
}
return res;
}
};
Python
class Solution:
def numberOfAlternatingGroups(self, colors: List[int]) -> int:
res = 0
n = len(colors)
for i in range(n):
pre = colors[i]
cur = colors[(i + 1) % n]
nxt = colors[(i + 2) % n]
if pre != cur and cur != nxt:
res += 1
return res
Java
class Solution {
public int numberOfAlternatingGroups(int[] colors) {
int res = 0;
int n = colors.length;
for (int i = 0; i < n; ++i) {
int pre = colors[i];
int cur = colors[(i + 1) % n];
int nxt = colors[(i + 2) % n];
if (pre != cur && cur != nxt) ++res;
}
return res;
}
}
JavaScript
/**
* @param {number[]} colors
* @return {number}
*/
var numberOfAlternatingGroups = function (colors) {
var res = 0;
for (var i = 0; i < colors.length; ++i) {
var pre = colors[i];
var cur = colors[(i + 1) % n];
var nxt = colors[(i + 2) % n];
if (pre !== cur && cur !== nxt) ++res;
}
return res;
};