Alternating Groups II - Problem
There is a circle of red and blue tiles. You are given an array of integers colors and an integer k.
The color of tile i is represented by colors[i]:
colors[i] == 0means that tileiis redcolors[i] == 1means that tileiis blue
An alternating group is every k contiguous tiles in the circle with alternating colors (each tile in the group except the first and last one has a different color from its left and right tiles).
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.
Input & Output
Example 1 — Basic Alternating Pattern
$
Input:
colors = [0,1,0,1,0], k = 3
›
Output:
3
💡 Note:
The alternating groups are: [0,1,0] starting at index 0, [1,0,1] starting at index 1, and [0,1,0] starting at index 2. Since it's circular, indices wrap around.
Example 2 — Partial Alternating
$
Input:
colors = [0,1,0,0,1], k = 4
›
Output:
0
💡 Note:
No group of 4 consecutive tiles alternates. For example, [0,1,0,0] has two consecutive 0s, so it doesn't alternate.
Example 3 — All Same Color
$
Input:
colors = [1,1,1], k = 2
›
Output:
0
💡 Note:
All tiles are the same color, so no alternating groups of any size exist.
Constraints
- 3 ≤ colors.length ≤ 105
- 1 ≤ k ≤ colors.length
- colors[i] is either 0 or 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Circular array of red (0) and blue (1) tiles, target group size k
2
Process
Find all k consecutive tiles that alternate in color
3
Output
Count of valid alternating groups
Key Takeaway
🎯 Key Insight: Track alternating segment lengths and calculate how many k-groups each segment can form
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code