Extend the Array: To handle the circular nature of the array, extend the colors
array by appending the first k-1
elements to its end. This allows us to easily check for alternating groups that wrap around the end of the array.
Initialize Counters:
res
to store the number of alternating groups.cnt
to count the length of the current alternating group.Iterate Through the Extended Array:
cnt
counter.cnt
counter to 1.cnt
counter reaches k
, increment the res
counter as it indicates the end of an alternating group.Return the Result: Finally, return the res
counter, which represents the number of alternating groups of length k
.