Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created March 9, 2025 18:30
Show Gist options
  • Save tatsuyax25/86c481e848067cc3276f8567168a1ef6 to your computer and use it in GitHub Desktop.
Save tatsuyax25/86c481e848067cc3276f8567168a1ef6 to your computer and use it in GitHub Desktop.
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 g
/**
* @param {number[]} colors
* @param {number} k
* @return {number}
*/
var numberOfAlternatingGroups = function(colors, k) {
// Extend the colors array to handle the circular nature by appending the first (k - 1) elements to the end
colors.push(...colors.slice(0, k - 1));
let count = 0; // Counter for the number of alternating groups
let left = 0; // Left pointer for the sliding window
// Iterate through the extended colors array with the right pointer
for (let right = 0; right < colors.length; right++) {
// If the current tile is the same color as the previous tile, reset the left pointer
if (right > 0 && colors[right] === colors[right - 1]) {
left = right;
}
// If the current window size (right - left + 1) is at least k, count it as an alternating group
if (right - left + 1 >= k) {
count++;
}
}
return count; // Return the total number of alternating groups
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment