Alternating Groups I - Problem

Imagine a beautiful circular mosaic made of red and blue tiles arranged in a perfect circle. You're tasked with finding all the alternating groups - special patterns where three consecutive tiles create a striking visual contrast.

Given an array colors representing the circular arrangement of tiles:

  • colors[i] == 0 means tile i is red
  • colors[i] == 1 means tile i is blue

An alternating group is formed by any 3 consecutive tiles where the middle tile has a different color from both its neighbors. Since the tiles form a circle, the first and last tiles are considered adjacent.

Goal: Count how many alternating groups exist in this circular mosaic.

Input & Output

example_1.py โ€” Basic Case
$ Input: colors = [0, 1, 0, 0, 1]
โ€บ Output: 3
๐Ÿ’ก Note: The alternating groups are: [0,1,0] at positions (0,1,2), [1,0,0] at positions (1,2,3), and [1,0,1] at positions (4,0,1) due to circular nature.
example_2.py โ€” All Same Color
$ Input: colors = [0, 0, 0]
โ€บ Output: 0
๐Ÿ’ก Note: No alternating groups exist since all tiles have the same color. No middle tile can differ from its neighbors.
example_3.py โ€” Alternating Pattern
$ Input: colors = [0, 1, 0, 1]
โ€บ Output: 4
๐Ÿ’ก Note: All possible groups of 3 are alternating: [0,1,0], [1,0,1], [0,1,0], and [1,0,1] (circular wrapping).

Constraints

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

Visualization

Tap to expand
01001Group 1: 0โ†’1โ†’0 โœ“Alternating Groups in Circular ArrayEach valid group has a middle tile different from both neighbors
Understanding the Visualization
1
Circular Setup
Arrange tiles in a circle where first and last tiles are adjacent
2
Pattern Recognition
Look for groups where middle tile differs from both neighbors
3
Count Valid Groups
Each position can be the center of at most one alternating group
4
Handle Boundaries
Use modulo arithmetic to seamlessly handle circular wrapping
Key Takeaway
๐ŸŽฏ Key Insight: In a circular array, we can check each position as a potential middle tile of an alternating group, using modulo arithmetic to handle the circular boundary seamlessly.
Asked in
Meta 25 Google 18 Amazon 15 Microsoft 12
24.6K Views
Medium Frequency
~12 min Avg. Time
892 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