3206. Alternating Groups I LeetCode Solution

In this guide, you will get 3206. Alternating Groups I LeetCode Solution with the best time and space complexity. The solution to Alternating Groups I problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Alternating Groups I solution in C++
  4. Alternating Groups I solution in Java
  5. Alternating Groups I solution in Python
  6. Additional Resources
3206. Alternating Groups I LeetCode Solution image

Problem Statement of Alternating Groups I

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

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

3206. Alternating Groups I LeetCode Solution in C++

class Solution {
 public:
  int numberOfAlternatingGroups(vector<int>& colors) {
    const int n = colors.size();
    int ans = 0;

    for (int i = 0; i < n; ++i)
      if (colors[i] != colors[(i - 1 + n) % n] &&
          colors[i] != colors[(i + 1) % n])
        ++ans;

    return ans;
  }
};
/* code provided by PROGIEZ */

3206. Alternating Groups I LeetCode Solution in Java

class Solution {
  public int numberOfAlternatingGroups(int[] colors) {
    final int n = colors.length;
    int ans = 0;

    for (int i = 0; i < n; ++i)
      if (colors[i] != colors[(i - 1 + n) % n] && colors[i] != colors[(i + 1) % n])
        ++ans;

    return ans;
  }
}
// code provided by PROGIEZ

3206. Alternating Groups I LeetCode Solution in Python

class Solution:
  def numberOfAlternatingGroups(self, colors: list[int]) -> int:
    n = len(colors)
    return sum(colors[i] != colors[i - 1] and
               colors[i] != colors[(i + 1) % n]
               for i in range(n))
# code by PROGIEZ

Additional Resources

See also  2058. Find the Minimum and Maximum Number of Nodes Between Critical Points LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.