There is a circle of red and blue tiles. You are given an array of integers colors and an integer k, where colors[i] is the color of tile i:
-
colors[i] == 0
means tile
i
is red.
-
colors[i] == 1
means tile
i
is blue.
A group of k consecutive tiles in the circle is an alternating group when its colors alternate: each tile in the group differs from its adjacent tiles in the group.
Return the number of alternating groups. Since colors represents a circle, the first and the last tiles are next to each other.
Function Signature
def number_of_alternating_groups(colors: list[int], k: int) -> int:
Rules
-
A group is identified by its starting index
s
: it is the tiles at indices
s, (s + 1) % n, ..., (s + k - 1) % n
, where
n = len(colors)
. There are exactly
n
candidate groups, one per starting index, and the answer counts how many of them alternate.
-
A group alternates when every two consecutive tiles inside it have different colors. The group's last tile and its first tile are not compared, even when
k == n
and they happen to touch on the circle.
-
Groups with different starting indices count separately, even if they have the same colors.
Constraints
-
3 <= len(colors) <= 10^5
-
0 <= colors[i] <= 1
-
3 <= k <= len(colors)
Examples
Input: colors = [0,1,0,1,0], k = 3
Output: 3
The groups starting at indices 0, 1 and 2 are [0,1,0], [1,0,1] and [0,1,0], and all alternate. The group starting at index 3 is [1,0,0] and the one starting at index 4 is [0,0,1]; both contain the two adjacent red tiles at indices 4 and 0.
Input: colors = [0,1,0,0,1,0,1], k = 6
Output: 2
The only two neighboring tiles with the same color are at indices 2 and 3. The groups starting at index 3 ([0,1,0,1,0,1], wrapping to index 1) and at index 4 ([1,0,1,0,1,0], wrapping to index 2) avoid that pair. Every other start includes it.
Input: colors = [0,1,0], k = 3
Output: 1
Here k == n. The group starting at index 0 is [0,1,0] and alternates; its last and first tiles are not compared. The groups starting at indices 1 and 2 are [1,0,0] and [0,0,1], which do not.