Alternating Groups II Problem
Description
LeetCode Problem 3208.
There is a circle of red and blue tiles. You are given an array of integers colors and an integer k. The color of tile i is represented by colors[i]:
colors[i] == 0means that tileiis red.colors[i] == 1means that tileiis blue.
An alternating group is every k contiguous tiles in the circle with alternating colors (each tile in the group except the first and last one has a different color from its left and right tiles).
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 = [0,1,0,1,0], k = 3
Output: 3
Explanation:

Alternating groups:



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

Alternating groups:


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

Constraints:
3 <= colors.length <= 10^50 <= colors[i] <= 13 <= k <= colors.length
Solution
Approach: Single Pass over the Unrolled Circle
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], k: int) -> int:
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