Alternating Groups I - Problem
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] == 0means that tile i is redcolors[i] == 1means 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: Since colors represents a circle, the first and the last tiles are considered to be next to each other.
Input & Output
Example 1 — Basic Circle
$
Input:
colors = [0,1,0,0,1]
›
Output:
2
💡 Note:
Position 1: colors[0,1,2] = [0,1,0] - middle 1 differs from both 0s ✓. Position 4: colors[3,4,0] = [0,1,0] - middle 1 differs from both 0s ✓. Total: 2 groups.
Example 2 — No Alternating
$
Input:
colors = [0,1,1,0,1]
›
Output:
1
💡 Note:
Only position 3 forms alternating group: colors[2,3,4] = [1,0,1] - middle 0 differs from both 1s ✓. Other positions don't form alternating patterns.
Example 3 — All Same Color
$
Input:
colors = [1,1,1]
›
Output:
0
💡 Note:
All tiles are same color (blue), so no middle tile can differ from its neighbors. No alternating groups possible.
Constraints
- 3 ≤ colors.length ≤ 100
- 0 ≤ colors[i] ≤ 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Circular array of 0s and 1s representing tile colors
2
Process
Find groups where middle tile differs from neighbors
3
Output
Count of alternating groups found
Key Takeaway
🎯 Key Insight: Use modular arithmetic to handle circular array wraparound when checking neighbors
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code