Loading
There is a circle of red and blue tiles. You are given an array of integers colors and an integer k. 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.
An alternating group is every k contiguous tiles in the circle with alternating colors (each tile in the group except the first and last one has a different color from its left and right tiles).
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.
Output: 3
Explanation:
Editorial
This is the editorial content for the problem. It would contain a detailed explanation of the solution approach.
Approach 1: Brute Force
We can check each possible group of k contiguous tiles and count how many of them have alternating colors.
Approach 2: Optimized Solution
A more efficient approach would be to use a sliding window technique to check for alternating patterns.
Complexity Analysis
Time Complexity: O(n)Space Complexity: O(1)
Community Solutions
Solution by User123
A clean C# implementation with O(n) time complexity.
public int NumberOfAlternatingGroups(int[] colors, int k) { int n = colors.Length; int count = 0; for (int i = 0; i < n; i++) { bool isAlternating = true; for (int j = i + 1; j < i + k - 1; j++) { if (colors[j % n] == colors[(j - 1) % n]) { isAlternating = false; break; } } if (isAlternating) count++; } return count; }
Solution by CodeMaster
An elegant Python solution using circular array properties.
def numberOfAlternatingGroups(self, colors: List[int], k: int) -> int: n = len(colors) count = 0 # Extend the array to handle circular property extended_colors = colors + colors[:k-1] for i in range(n): if all(extended_colors[i+j] != extended_colors[i+j+1] for j in range(k-1)): count += 1 return count
Your Submissions
You haven't submitted any solutions for this problem yet.