#3206
Easy Algorithms Alternating groups i
Array Sliding Window
68.8% acceptance
Feb 25, 2026
169
10
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn number_of_alternating_groups(colors: Vec<i32>) -> i32 {
let n = colors.len();
let mut count = 0;
for i in 0..n {
if colors[i] != colors[(i + 1) % n] && colors[(i + 1) % n] != colors[(i + 2) % n] {
count += 1;
}
}
count
}
}