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] == 0 means that tile i is red
  • colors[i] == 1 means that tile i is 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
Alternating Groups II: Find k-length alternating patternsInput: colors = [0,1,0,1,0], k = 301010Circular Array (indices wrap around)Valid Groups of size 3:[0,1,0], [1,0,1], [0,1,0]Each group has 3 consecutivetiles with alternating colorsOutput: 3 alternating groups found
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
Asked in
Google 25 Microsoft 20 Amazon 15
32.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen