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] == 0means that tileiis red.colors[i] == 1means that tileiis 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 <= 1050 <= colors[i] <= 13 <= k <= colors.length
Solution
First:
- Colours are represented using integers:
0for red,1for blue. kis the size of the group to check.- The array
colorsrepresents 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
kis 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
colorswith itself. - Check all possible windows of size
kin 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), wherekis sliding window size andnis size of the input array. - 🧺 Space complexity:
O(n)as the extended array requiresO(n)additional memory.