Problem
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 tilei
is red.colors[i] == 1
means that tilei
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.
Examples
Example 1:
|
|
Alternating groups:
Example 2:
|
|
Alternating groups:
Example 3:
|
|
Constraints
3 <= colors.length <= 105
0 <= colors[i] <= 1
3 <= k <= colors.length
Solution
First:
- Colours are represented using integers:
0
for red,1
for blue. k
is the size of the group to check.- The array
colors
represents a circular arrangement of tiles, meaning the last and first elements are adjacent in the circle.
Method 1 - Sliding Window
Here are group properties:
- A group of size
k
is alternating if: - Each tile alternates in colour with its neighbours. - For a valid group:
- If the first tile is 0 (red), the expected sequence alternates as
0, 1, 0, 1...
. - If the first tile is 1 (blue), the expected sequence alternates as
1, 0, 1, 0...
.
- If the first tile is 0 (red), the expected sequence alternates as
Because input is circular, extend the colours array by concatenating a copy of itself. This way, we can perform straightforward index-based checks across the potentially end-overlapping groups.
Algorithms
- Extend the array by concatenating
colors
with itself. - Check all possible windows of size
k
in the extended array. - Compare each potential group with a valid alternating pattern.
- Count the number of valid groups.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(k * n)
, wherek
is sliding window size andn
is size of the input array. - 🧺 Space complexity:
O(n)
as the extended array requiresO(n)
additional memory.