Array Sliding Window 3206. Alternating Groups I ¶ Time: $O(n)$ Space: $O(1)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14class Solution { public: int numberOfAlternatingGroups(vector<int>& colors) { const int n = colors.size(); int ans = 0; for (int i = 0; i < n; ++i) if (colors[i] != colors[(i - 1 + n) % n] && colors[i] != colors[(i + 1) % n]) ++ans; return ans; } }; 1 2 3 4 5 6 7 8 9 10 11 12class Solution { public int numberOfAlternatingGroups(int[] colors) { final int n = colors.length; int ans = 0; for (int i = 0; i < n; ++i) if (colors[i] != colors[(i - 1 + n) % n] && colors[i] != colors[(i + 1) % n]) ++ans; return ans; } } 1 2 3 4 5 6class Solution: def numberOfAlternatingGroups(self, colors: list[int]) -> int: n = len(colors) return sum(colors[i] != colors[i - 1] and colors[i] != colors[(i + 1) % n] for i in range(n))