You are given a circle of red and blue tiles represented by an array of integers colors
. 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.Every 3 contiguous tiles in the circle with alternating colors (the middle tile has a different color from its left and right tiles) is called an alternating group.
Your task is to implement a function that takes the colors
array as input and returns 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.
For example:
colors = [1, 1, 1]
should return 0
because there are no alternating groups.colors = [0, 1, 0, 0, 1]
should return 3
because there are three alternating groups: [0, 1, 0]
, [1, 0, 0]
, and [0, 0, 1]
considering the circular nature, becomes [1,0,1]
.Explain your approach, its time and space complexity, and handle edge cases appropriately.
The brute force approach is to iterate through the colors
array and check for each group of three contiguous tiles if they form an alternating group. Since the tiles are arranged in a circle, we need to handle the wrap-around case where the first and last tiles are considered adjacent.
colors
array from index 0 to n-1
, where n
is the length of the array.i
, check if the tiles at indices i
, (i+1)%n
, and (i+2)%n
form an alternating group.colors[i]
!= colors[(i+1)%n]
and colors[(i+1)%n]
!= colors[(i+2)%n]
.def count_alternating_groups_naive(colors):
n = len(colors)
count = 0
for i in range(n):
if colors[i] != colors[(i + 1) % n] and colors[(i + 1) % n] != colors[(i + 2) % n]:
count += 1
return count
The optimal solution is essentially the same as the naive solution because we must inspect each possible group of three contiguous tiles to determine if it's an alternating group. Therefore, there's no way to significantly improve upon the naive solution in terms of time complexity.
(Same as the naive solution)
colors
array from index 0 to n-1
, where n
is the length of the array.i
, check if the tiles at indices i
, (i+1)%n
, and (i+2)%n
form an alternating group.colors[i]
!= colors[(i+1)%n]
and colors[(i+1)%n]
!= colors[(i+2)%n]
.def count_alternating_groups_optimal(colors):
n = len(colors)
count = 0
for i in range(n):
if colors[i] != colors[(i + 1) % n] and colors[(i + 1) % n] != colors[(i + 2) % n]:
count += 1
return count
Both the naive and optimal solutions have a time complexity of O(n) and a space complexity of O(1). The key is to correctly handle the circular nature of the array by using the modulo operator (%
).