Dare2Solve
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.
class Solution {
public:
int numberOfAlternatingGroups(vector<int>& 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;
}
};
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
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;
}
}
/**
* @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;
};