3206. Alternating Groups I

Dare2Solve

Dare2Solve

3206. Alternating Groups I
SAMSUNG 49-Inch Odyssey G9
SAMSUNG 49-Inch Odyssey G9
Because earth is not flat

Intuition

In this problem, we need to find groups of three contiguous tiles in a circular array where the middle tile is a different color than its left and right neighbors. This means we need to check each triplet of tiles in the array to see if they alternate in color.

Approach

  1. Initialization: Start by initializing a counter to keep track of the number of alternating groups.
  2. Iterate through the array: Loop through each tile in the array. Since the array is circular, we need to handle the wrapping around at the ends of the array.
  3. Check alternating condition: For each tile, check the colors of the current tile, the next tile, and the tile after that. Use modulo operation to wrap around the array.
  4. Update counter: If the colors alternate (i.e., the middle tile is different from the other two), increment the counter.
  5. Return result: After checking all possible triplets, return the counter.

Complexity

Code

C++

class Solution {
public:
    int numberOfAlternatingGroups(vector<int>& colors) {
        int res = 0;
        int n = colors.size();
        for (int i = 0; i < n; ++i) {
            int pre = colors[i];
            int cur = colors[(i + 1) % n];
            int nxt = colors[(i + 2) % n];
            if (pre != cur && cur != nxt) ++res;
        }
        return res;
    }
};

Python

class Solution:
    def numberOfAlternatingGroups(self, colors: List[int]) -> int:
        res = 0
        n = len(colors)
        for i in range(n):
            pre = colors[i]
            cur = colors[(i + 1) % n]
            nxt = colors[(i + 2) % n]
            if pre != cur and cur != nxt:
                res += 1
        return res

Java

class Solution {
    public int numberOfAlternatingGroups(int[] colors) {
        int res = 0;
        int n = colors.length;
        for (int i = 0; i < n; ++i) {
            int pre = colors[i];
            int cur = colors[(i + 1) % n];
            int nxt = colors[(i + 2) % n];
            if (pre != cur && cur != nxt) ++res;
        }
        return res;
    }
}

JavaScript

/**
 * @param {number[]} colors
 * @return {number}
 */
var numberOfAlternatingGroups = function (colors) {
    var res = 0;
    for (var i = 0; i < colors.length; ++i) {
        var pre = colors[i];
        var cur = colors[(i + 1) % n];
        var nxt = colors[(i + 2) % n];
        if (pre !== cur && cur !== nxt) ++res;
    }
    return res;
};