Skip to main content

Alternating Groups I - Solution & Explanation

EasyArraySliding Window16 min readAsked at: Amazon, Samsara, Google
Practice this problem

Problem Statement

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 that since colors represents a circle, the first and the last tiles are considered to be next to each other.

 

Example 1:

Input: colors = [1,1,1]

Output: 0

Explanation:

Example 2:

Input: colors = [0,1,0,0,1]

Output: 3

Explanation:

Alternating groups:

 

Constraints:

  • 3 <= colors.length <= 100
  • 0 <= colors[i] <= 1

Approach Overview

Problem Overview: You are given a circular colors array where each value represents a tile color. A group is valid if three consecutive tiles form an alternating pattern (for example 0,1,0 or 1,0,1). Because the array is circular, the sequence can wrap from the end back to the start. The task is to count how many length-3 groups satisfy this alternating rule.

Approach 1: Iterative Pattern Check (O(n) time, O(1) space)

Iterate through every index i and examine the next two elements using circular indexing. A valid alternating group occurs when colors[i] != colors[i+1] and colors[i+1] != colors[i+2]. These two comparisons guarantee the pattern flips at each step. Use modulo arithmetic to wrap indices: (i + 1) % n and (i + 2) % n. This approach simply scans the array once, performs constant comparisons per index, and increments a counter when the condition holds. The logic is straightforward and works well when the group size is fixed.

This technique relies purely on sequential iteration over the array. Since only three values are inspected at a time, memory usage stays constant and the runtime grows linearly with the number of tiles.

Approach 2: Sliding Window (O(n) time, O(1) space)

A more general way to reason about the problem is with a fixed-size sliding window of length 3. Start with the first three elements and verify whether they alternate. Then slide the window forward by one position at a time while maintaining circular indexing. Each shift removes the leftmost element and includes the next element in the circle.

The key insight is that the window validity depends only on two adjacent comparisons: a != b and b != c. Every time the window moves, recompute these comparisons for the new triplet. Because the window size never changes, each step performs constant work. The circular property is handled by indexing with modulo so the window naturally wraps from the last element to the first.

This method is conceptually useful because it mirrors how many larger alternating-pattern problems are solved. When group sizes become variable or constraints increase, the sliding window pattern scales better than hardcoding comparisons.

Recommended for interviews: The sliding window explanation is typically preferred. Interviewers expect you to recognize the alternating constraint as a local window property and scan the array in O(n) time with constant memory. The direct iteration solution also runs in linear time and clearly demonstrates understanding, but framing it as a window problem shows stronger familiarity with common algorithm patterns.

Approach 1: Iterative Approach

This approach iteratively checks each possible set of three consecutive tiles (considering the circle property) to determine if they form an alternating group. By ensuring the middle tile has a different color from its adjacent tiles, we can count these groups effectively.

The code uses a loop to iterate through each tile. For each tile, it checks a group formed by the current tile and the next two, using modulo arithmetic to wrap around the array index when necessary. It checks if the middle tile is not equal to both its adjacent tiles and increments the counter if true.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) where n is the number of tiles.
Space Complexity: O(1) because no extra space is used except for a few variables.

Try this approach in the editor →

Approach 2: Optimized Sliding Window Approach

This approach uses a sliding window technique to optimize the checking of three consecutive tiles by keeping track of just the current sequence of three tiles. It moves the window one tile forward at each step, efficiently checking each group and counting the valid alternating groups.

Using a variable window of size three that shifts across the circular array, the implementation ensures each pass only checks a small, bounded portion of the array. This limits the overhead of condition checks and can quickly pivot to the next group.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) where n is the number of tiles.
Space Complexity: O(1) because it requires no additional space beyond in-place modifications.

Try this approach in the editor →

Approach 3: Single Pass

We set k = 3, indicating that the length of the alternating group is 3.

For convenience, we can unfold the ring into an array of length 2n and then traverse this array from left to right. We use a variable cnt to record the current length of the alternating group. If we encounter the same color, we reset cnt to 1; otherwise, we increment cnt. If cnt \ge k and the current position i is greater than or equal to n, then we have found an alternating group, and we increment the answer by one.

After the traversal, we return the answer.

The time complexity is O(n), where n is the length of the array colors. The space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Iterative Approach

Time Complexity: O(n) where n is the number of tiles.
Space Complexity: O(1) because no extra space is used except for a few variables.

Optimized Sliding Window Approach

Time Complexity: O(n) where n is the number of tiles.
Space Complexity: O(1) because it requires no additional space beyond in-place modifications.

Single Pass—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Iterative Pattern CheckO(n)O(1)Best when the group size is fixed (3) and you want the simplest implementation.
Sliding WindowO(n)O(1)Preferred conceptual approach for pattern detection problems and scalable to larger window sizes.

Video Solution

3206 & 3208. Alternating Groups II | 3206. Alternating Groups I | Not Sliding Window • Aryan Mittal • 6,576 views views

Watch 5 more video solutions →

Frequently Asked Questions

Is Alternating Groups I easy or hard?
Alternating Groups I is classified as Easy. The logic involves simple array traversal and checking adjacent differences, making it a common warm-up problem for sliding window and circular array concepts.
Alternating Groups I Python/Java solution
Both Python and Java implementations iterate through the array and compare three consecutive elements using modulo indexing for circular behavior. Each iteration performs two comparisons and increments a counter when the alternating condition holds.
How to solve Alternating Groups I in O(n)?
Iterate through the circular array and inspect every triplet of consecutive elements. Use modulo indexing so the last elements wrap back to the start. Count the position if colors[i] != colors[i+1] and colors[i+1] != colors[i+2]. This single pass produces an O(n) solution.
What is the best approach for Alternating Groups I?
The best approach is a linear scan using a fixed sliding window of size three. For each index, check whether colors[i] != colors[i+1] and colors[i+1] != colors[i+2] while handling circular indexing with modulo. This runs in O(n) time and O(1) space.
Is Alternating Groups I asked at Google/Amazon/Meta?
Alternating pattern problems frequently appear in interviews at companies like Amazon, Google, and Meta because they test array traversal and pattern recognition. Variants involving sliding window or circular arrays are common in coding interviews.
What data structure is used in Alternating Groups I?
The problem primarily uses a simple array traversal with constant variables. No additional data structures are required, though the solution conceptually uses a sliding window over the array.
What is the time complexity of Alternating Groups I?
The optimal solution runs in O(n) time because each index in the array is checked once. Only constant comparisons are performed for each position, and no additional data structures are required, resulting in O(1) space complexity.

Ready to solve this problem?

Practice Alternating Groups I with our built-in code editor and test cases.

Practice on FleetCode