Talentd
FleetCode
Make and follow sheets.Sign in

Alternating Groups I solution and explanation

EasyArraySliding Window5 min read69.5% acceptanceUpdated 9 Apr 2026
3206 & 3208. Alternating Groups II | 3206. Alternating Groups I | Not Sliding WindowAryan Mittal · 16:32 · 6K viewsWatch on YouTube
5 more videos on this problem
  1. 3206 & 3208. Alternating Groups II | 3206. Alternating Groups I | Not Sliding WindowAryan Mittal · 16:32 · 6K views
  2. Leetcode 3206 Alternating Groups IAlgorithms Casts · 7:43 · 702 views
  3. 3206. Alternating Groups I (Leetcode Easy)Programming Live with Larry · 3:01 · 313 views
  4. leetcode 3206 : alternating groups : python solutionleetcode blind 75 · 4:58 · 219 views
  5. Alternating Groups I | Leetcode Biweekly Contest 134 Solution | #leetcode | Ajit KushwahaAjit Kushwaha · 5:54 · 130 views
  6. 3206. Alternating Groups I (leetcode easy)Coder on A Farm · 3:47 · 109 views

The 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 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.

def count_alternating_groups(colors):
    count = 0
    size = len(colors)
    for i in range(size):
        prev = colors[i]
        curr = colors[(i + 1) % size]
        next = colors[(i + 2) % size]
        if curr != prev and curr != next:
            count += 1
    return count

colors = [0, 1, 0, 0, 1]
result = count_alternating_groups(colors)
print(f"Number of alternating groups: {result}")
public class AlternatingGroups {
    public static int countAlternatingGroups(int[] colors) {
        int count = 0;
        int size = colors.length;
        for (int i = 0; i < size; i++) {
            int prev = colors[i];
            int curr = colors[(i + 1) % size];
            int next = colors[(i + 2) % size];
            if (curr != prev && curr != next) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        int[] colors = {0, 1, 0, 0, 1};
        System.out.println("Number of alternating groups: " + countAlternatingGroups(colors));
    }
}
#include <iostream>
#include <vector>
using namespace std;

int countAlternatingGroups(const vector<int>& colors) {
    int count = 0;
    int size = colors.size();
    for (int i = 0; i < size; i++) {
        int prev = colors[i];
        int curr = colors[(i + 1) % size];
        int next = colors[(i + 2) % size];
        if (curr != prev && curr != next) {
            count++;
        }
    }
    return count;
}

int main() {
    vector<int> colors = {0, 1, 0, 0, 1};
    cout << "Number of alternating groups: " << countAlternatingGroups(colors) << endl;
    return 0;
}
function countAlternatingGroups(colors) {
    let count = 0;
    const size = colors.length;
    for (let i = 0; i < size; i++) {
        const prev = colors[i];
        const curr = colors[(i + 1) % size];
        const next = colors[(i + 2) % size];
        if (curr !== prev && curr !== next) {
            count++;
        }
    }
    return count;
}

const colors = [0, 1, 0, 0, 1];
console.log(`Number of alternating groups: ${countAlternatingGroups(colors)}`);
#include <stdio.h>

int countAlternatingGroups(int* colors, int colorsSize) {
    int count = 0;
    for (int i = 0; i < colorsSize; i++) {
        int prev = colors[i];
        int curr = colors[(i + 1) % colorsSize];
        int next = colors[(i + 2) % colorsSize];
        if (curr != prev && curr != next) {
            count++;
        }
    }
    return count;
}

int main() {
    int colors[] = {0, 1, 0, 0, 1};
    int result = countAlternatingGroups(colors, 5);
    printf("Number of alternating groups: %d\n", result);
    return 0;
}
using System;

class AlternatingGroups {
    public static int CountAlternatingGroups(int[] colors) {
        int count = 0;
        int size = colors.Length;
        for (int i = 0; i < size; i++) {
            int prev = colors[i];
            int curr = colors[(i + 1) % size];
            int next = colors[(i + 2) % size];
            if (curr != prev && curr != next) {
                count++;
            }
        }
        return count;
    }

    static void Main() {
        int[] colors = { 0, 1, 0, 0, 1 };
        Console.WriteLine("Number of alternating groups: " + CountAlternatingGroups(colors));
    }
}

The Python function leverages a simple loop to iterate over the colors list, examining each tile and its neighbors using modulus to handle the circular array condition. It counts how many groups satisfy the alternating condition.

Complexity

Time Complexity: O(n) where n is the number of tiles.
Space Complexity: O(1) since no extra data structures are used.

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.

def count_alternating_groups(colors):
    count = 0
    n = len(colors)
    for i in range(n):
        if colors[i] != colors[(i + 1) % n] and colors[(i + 1) % n] != colors[(i + 2) % n]:
            count += 1
    return count

colors = [0, 1, 0, 0, 1]
result = count_alternating_groups(colors)
print(f"Number of alternating groups: {result}")
public class AlternatingGroups {
    public static int countAlternatingGroups(int[] colors) {
        int count = 0;
        int n = colors.length;
        for (int i = 0; i < n; i++) {
            if (colors[i] != colors[(i + 1) % n] && colors[(i + 1) % n] != colors[(i + 2) % n]) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        int[] colors = {0, 1, 0, 0, 1};
        System.out.println("Number of alternating groups: " + countAlternatingGroups(colors));
    }
}
#include <iostream>
#include <vector>
using namespace std;

int countAlternatingGroups(const vector<int>& colors) {
    int count = 0;
    int size = colors.size();
    for (int i = 0; i < size - 2; i++) {
        if (colors[i] != colors[i + 1] && colors[i + 1] != colors[i + 2]) {
            count++;
        }
    }
    if (colors[size - 1] != colors[0] && colors[0] != colors[1]) count++;
    if (colors[size - 2] != colors[size - 1] && colors[size - 1] != colors[0]) count++;
    return count;
}

int main() {
    vector<int> colors = {0, 1, 0, 0, 1};
    cout << "Number of alternating groups: " << countAlternatingGroups(colors) << endl;
    return 0;
}
function countAlternatingGroups(colors) {
    let count = 0;
    const n = colors.length;
    for (let i = 0; i < n; i++) {
        if (colors[i] !== colors[(i + 1) % n] && colors[(i + 1) % n] !== colors[(i + 2) % n]) {
            count++;
        }
    }
    return count;
}

const colors = [0, 1, 0, 0, 1];
console.log(`Number of alternating groups: ${countAlternatingGroups(colors)}`);
#include <stdio.h>

int countAlternatingGroups(int* colors, int colorsSize) {
    int count = 0;
    for (int i = 0; i < colorsSize; i++) {
        int prev = colors[i];
        int curr = colors[(i + 1) % colorsSize];
        int next = colors[(i + 2) % colorsSize];
        if (curr != prev && curr != next) {
            count++;
        }
    }
    return count;
}

int main() {
    int colors[] = {0, 1, 0, 0, 1};
    int result = countAlternatingGroups(colors, 5);
    printf("Number of alternating groups: %d\n", result);
    return 0;
}
using System;

class AlternatingGroups {
    public static int CountAlternatingGroups(int[] colors) {
        int count = 0;
        int n = colors.Length;
        for (int i = 0; i < n; i++) {
            if (colors[i] != colors[(i + 1) % n] && colors[(i + 1) % n] != colors[(i + 2) % n]) {
                count++;
            }
        }
        return count;
    }

    static void Main() {
        int[] colors = { 0, 1, 0, 0, 1 };
        Console.WriteLine("Number of alternating groups: " + CountAlternatingGroups(colors));
    }
}

This implementation hinges on a sliding-window technique across the list, ensuring that the structure folds into itself, akin to array rotation for each step manually during execution.

Complexity

Time Complexity: O(n) where n is the number of tiles.
Space Complexity: O(1) as only momentary hold of variables are required.

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).

function numberOfAlternatingGroups(colors: number[]): number {
    const k = 3;
    const n = colors.length;
    let [ans, cnt] = [0, 0];
    for (let i = 0; i < n << 1; ++i) {
        if (i && colors[i % n] === colors[(i - 1) % n]) {
            cnt = 1;
        } else {
            ++cnt;
        }
        ans += i >= n && cnt >= k ? 1 : 0;
    }
    return ans;
}
func numberOfAlternatingGroups(colors []int) (ans int) {
	k := 3
	n := len(colors)
	cnt := 0
	for i := 0; i < n<<1; i++ {
		if i > 0 && colors[i%n] == colors[(i-1)%n] {
			cnt = 1
		} else {
			cnt++
		}
		if i >= n && cnt >= k {
			ans++
		}
	}
	return
}
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) since no extra data structures are used.

Optimized Sliding Window Approach

Time Complexity: O(n) where n is the number of tiles.
Space Complexity: O(1) as only momentary hold of variables are required.

Single Pass–

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.

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.

Comments

Now write it yourselfClose this page and solve Alternating Groups I in the editor, without looking.
Practise Alternating Groups I