Alternating Groups I - Problem

There is a circle of red and blue tiles. You are given an array of integers colors. 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

Every 3 contiguous tiles in the circle with alternating colors (the middle tile has a different color from its left and right tiles) is called an alternating group.

Return the number of alternating groups.

Note: Since colors represents a circle, the first and the last tiles are considered to be next to each other.

Input & Output

Example 1 — Basic Circle
$ Input: colors = [0,1,0,0,1]
Output: 2
💡 Note: Position 1: colors[0,1,2] = [0,1,0] - middle 1 differs from both 0s ✓. Position 4: colors[3,4,0] = [0,1,0] - middle 1 differs from both 0s ✓. Total: 2 groups.
Example 2 — No Alternating
$ Input: colors = [0,1,1,0,1]
Output: 1
💡 Note: Only position 3 forms alternating group: colors[2,3,4] = [1,0,1] - middle 0 differs from both 1s ✓. Other positions don't form alternating patterns.
Example 3 — All Same Color
$ Input: colors = [1,1,1]
Output: 0
💡 Note: All tiles are same color (blue), so no middle tile can differ from its neighbors. No alternating groups possible.

Constraints

  • 3 ≤ colors.length ≤ 100
  • 0 ≤ colors[i] ≤ 1

Visualization

Tap to expand
Alternating Groups I - Circular Array INPUT 0 1 2 3 4 = Red (0) = Blue (1) Input Array: colors = [0, 1, 0, 0, 1] Circular: last connects to first ALGORITHM STEPS 1 Check each triplet Iterate i from 0 to n-1 2 Get neighbors (circular) left=(i-1+n)%n, right=(i+1)%n 3 Check alternating mid != left AND mid != right 4 Count valid groups Increment count if valid Checking All Triplets: i=0: [1,0,1] alt? YES i=1: [0,1,0] alt? YES i=2: [1,0,0] alt? NO i=3: [0,0,1] alt? NO i=4: [0,1,0] alt? YES FINAL RESULT Valid Alternating Groups: Group 1: indices [4, 0, 1] 1 0 1 OK - Alternating! Group 2: indices [0, 1, 2] 0 1 0 OK - Alternating! OUTPUT 2 Total alternating groups Time: O(n), Space: O(1) Key Insight: An alternating group requires the middle tile to have a DIFFERENT color from BOTH its neighbors. For circular arrays, use modulo arithmetic: left = (i - 1 + n) % n, right = (i + 1) % n to handle wrap-around. This ensures the last element connects to the first, forming a complete circle. TutorialsPoint - Alternating Groups I | Optimal Solution O(n)
Asked in
Meta 15 Google 12
12.5K Views
Medium Frequency
~15 min Avg. Time
450 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