📝Description
📋Editorial
💡Solutions
📊Submissions

Loading

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.

Example 1:
Input: colors = [0,1,0,1,0], k = 3
Output: 3
Explanation:
Circle diagram

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.

Submission Statistics

Accepted: 1,245
Submissions: 3,782
Acceptance Rate: 32.9%
</>Code
Auto
đŸ“‘đŸ”„â†Šī¸đŸ”
Progress:0% | Errors:0| WPM:0
Tip: Press Tab to skip leading whitespace at the start of lines
✓ Testcase
Test Result
Case 1
Case 2
+
colors =
[0,1,0,1,0]
k =
3
colors =
[1,0,1,0,1,0]
k =
4

Test Results

✓ Accepted
Runtime: 56 ms
Memory: 42.1 MB
Output:
3
Expected:
3