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 INPUT 0 1 0 1 0 i=0 i=1 i=2 i=3 i=4 Red (0) Blue (1) Input Values: colors = [0,1,0,1,0] k = 3 ALGORITHM STEPS 1 Extend Array Handle circular wrap-around 2 Sliding Window Check k consecutive tiles 3 Check Alternating Each pair must differ 4 Count Valid Groups Increment counter Valid Groups (k=3): [0,1,0] [1,0,1] [0,1,0] i=0,1,2 i=1,2,3 i=2,3,4 *Two groups wrap around [1,0,0] and [0,0,1] not valid FINAL RESULT 0 1 0 1 0 Group 1 OUTPUT 3 3 alternating groups found OK - All groups verified Key Insight: Use a sliding window of size k to efficiently count alternating groups. Handle the circular nature by extending the array conceptually (append first k-1 elements). Track consecutive alternating count and reset when pattern breaks. Time: O(n), Space: O(1). TutorialsPoint - Alternating Groups II | Optimal Solution (Sliding Window)
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