[LeetCode] Alternating Groups I

3206. Alternating Groups I

There is a circle of red and blue tiles. You are given an array of integers colors. The color of tile i is represented by colors[i]:

  • colors[i] == 0 means that tile i is red.
  • colors[i] == 1 means that tile i is blue.

Every 3 contiguous tiles in the circle with alternating colors (the middle tile has a different color from its left and right tiles) is called an alternating group.

Return the number of alternating groups.

Note that since colors represents a circle, the first and the last tiles are considered to be next to each other.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int numberOfAlternatingGroups(vector<int>& A) {
int res = 0, n = A.size();
for(int i = 0; i < n; i++) {
if(A[i] != A[(i+1)%n]) {
if(A[i] == A[(i+2)%n]) res++;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/07/06/PS/LeetCode/alternating-groups-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.