Alternating Groups I Problem
Description
LeetCode Problem 3206.
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] == 0means that tileiis red.colors[i] == 1means that tileiis 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.
Example 1:
Input: colors = [1,1,1]
Output: 0
Explanation:

Example 2:
Input: colors = [0,1,0,0,1]
Output: 3
Explanation:

Alternating groups:



Constraints:
3 <= colors.length <= 1000 <= colors[i] <= 1
Solution
Approach: Single Pass over the Unrolled Circle
Here the group length is k = 3. To handle the circle, walk over the array twice (indices 0 to 2n - 1, reading colors[i % n]).
Keep cnt, the length of the alternating run ending at the current tile: reset it to 1 when the color equals the previous tile's color, otherwise increase it. Count a group whenever cnt >= k and i >= n; restricting to the second lap makes each starting position counted exactly once.
Complexity: O(n) time and O(1) space.
class Solution:
def numberOfAlternatingGroups(self, colors: List[int]) -> int:
k = 3
n = len(colors)
ans = cnt = 0
for i in range(n << 1):
if i and colors[i % n] == colors[(i - 1) % n]:
cnt = 1
else:
cnt += 1
ans += i >= n and cnt >= k
return ans