Alternating Groups II - Problem

Imagine a circular necklace made of red and blue beads arranged in a perfect circle. Your task is to find all the alternating patterns of exactly k consecutive beads where no two adjacent beads have the same color!

You're given:

  • An array colors where colors[i] = 0 represents a red bead and colors[i] = 1 represents a blue bead
  • An integer k representing the length of each group to check

What makes a valid alternating group?
A group of k consecutive beads is alternating if each bead (except the first and last) has a different color from both its neighbors. Since the beads form a circle, the last bead connects back to the first bead.

Goal: Return the total number of valid alternating groups of size k.

Input & Output

example_1.py โ€” 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 (wrapping around). Each group has exactly 3 elements with alternating colors.
example_2.py โ€” Broken alternating sequence
$ Input: colors = [0,1,0,0,1], k = 4
โ€บ Output: 0
๐Ÿ’ก Note: No group of 4 consecutive elements has alternating colors. The sequence breaks at positions 2-3 where we have [0,0], so no valid alternating group of length 4 exists.
example_3.py โ€” Single element groups
$ Input: colors = [1,1,0,1], k = 1
โ€บ Output: 4
๐Ÿ’ก Note: When k=1, every single element forms a valid alternating group by definition. There are 4 elements, so we have 4 groups.

Constraints

  • 3 โ‰ค colors.length โ‰ค 105
  • colors[i] is either 0 or 1
  • 1 โ‰ค k โ‰ค colors.length
  • The array represents a circular arrangement

Visualization

Tap to expand
01010101Alternating Groups DetectionStreak length: 8For k=3: 6 valid groupsFor k=4: 5 valid groupsFor k=5: 4 valid groups
Understanding the Visualization
1
Walk around the circle
Start at any bead and walk around the circular necklace, comparing each bead with its neighbor
2
Track alternating streaks
Keep count of how many consecutive beads alternate in color - this is your 'streak length'
3
Identify valid patterns
Whenever your streak length reaches k or more, you've found locations where k-length alternating patterns exist
4
Count all possibilities
A streak of length L contains (L-k+1) different k-length alternating patterns starting at different positions
Key Takeaway
๐ŸŽฏ Key Insight: Instead of checking each k-window separately (O(nk)), track the alternating streak length in a single pass (O(n)). A streak of length Lโ‰ฅk contains exactly (L-k+1) valid k-windows!
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
28.5K Views
Medium-High Frequency
~25 min Avg. Time
867 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