Problem Description
Given a circular array "colors" of tiles—where 0 represents a red tile and 1 represents a blue tile—every group of 3 contiguous tiles is considered an "alternating group" if the middle tile's color is different from both its left and right neighbors. Since the tiles are arranged in a circle, the first and last tiles are neighbors. The task is to count the number of such alternating groups.
Key Insights
- The circular nature means that the neighbor of the first tile includes the last tile and vice versa.
- For each tile (considered the middle of a triple), check if it is not equal to its left neighbor and not equal to its right neighbor.
- A simple one-pass iteration over the array (using modulus arithmetic) is sufficient to evaluate every group of three.
- Since only a constant number (3) of elements are compared for each index, the operation is efficient.
Space and Time Complexity
Time Complexity: O(n), where n is the number of tiles. Space Complexity: O(1), as we use only a fixed number of extra variables.
Solution
The idea is to iterate through the array considering each tile as the center of a group of three by using the circular indexing technique. For each index i, determine its left neighbor at (i - 1 + n) % n and right neighbor at (i + 1) % n. Check if the color at the center is different from both of these neighbors. If so, increase the count of alternating groups. This approach only requires a single pass over the array, ensuring an optimal solution with O(n) time complexity.