3206. Alternating Groups I
Problem Description
There is a circle of red and blue tiles. You are given an array of integers colors
. 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.
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.
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.
Intuition
To solve this problem, imagine the circle of tiles as a linear array repeated twice to account for the circular nature. This helps to simply check for alternating groups involving the first and last elements.
We define a group of size 3
as an alternating group if the middle tile is different from its neighbors. By iterating through the extended array, we maintain a count of consecutive pairs that have different colors. Whenever we encounter a pair of tiles with the same color, we reset the count. Any time this count reaches or exceeds 3
after considering the first n
tiles and extending beyond them, it indicates we've found an alternating group.
The key is recognizing the circular structure of the problem, which is elegantly handled by doubling the array to streamline the logic of checking neighbors when wrapping around the end.
Learn more about Sliding Window patterns.
Solution Approach
The solution utilizes a single-pass approach with the help of an unfolded circular array. Here's a detailed walkthrough:
-
Setting Up Variables:
k
is set to3
, as we're interested in groups of three tiles.n
is the length of thecolors
array, representing the original circle of tiles.ans
is initialized to count the number of detected alternating groups.cnt
is used to track the current alternating sequence's length.
-
Unfolding the Circle:
- By iterating over
2n
(doubling the array length), we effectively simulate the circular nature of the tiles. This allows us to seamlessly check the transitions from end to start, considering continuity without manually implementing wrap-around logic.
- By iterating over
-
Iteration:
- For each index
i
from0
to2n-1
, thecurrent
tile iscolors[i % n]
. This modulo operation ensures we wrap around the array naturally. - If
i > 0
and thecurrent
tile is the same color as theprevious
tile, we resetcnt
to1
since no alternating sequence can continue. - Otherwise, increment
cnt
because the alternating condition is maintained.
- For each index
-
Counting Alternating Groups:
- For any index
i
that is greater than or equal ton
and wherecnt
is at leastk
, an alternating group has been confirmed. Incrementans
in such cases.
- For any index
-
Final Result:
- Return
ans
as the total number of detected alternating groups.
- Return
This approach effectively and efficiently identifies alternating groups while respecting the circular structure by simulating a linear traversal.
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through an example using the array colors = [0, 1, 0, 1, 0]
to illustrate the solution approach.
-
Understanding the Input:
- The array
colors
represents a circle of tiles with the sequence of colors as Red, Blue, Red, Blue, Red.
- The array
-
Setting Up Variables:
k = 3
, representing the length of the alternating group we're inspecting.n = 5
, the length of thecolors
array.- Initialize
ans = 0
to track the number of alternating groups. - Start with
cnt = 1
, a counter to track consecutive alternating patterns.
-
Simulating the Circle:
- We effectively consider the array as
colors = [0, 1, 0, 1, 0, 0, 1, 0, 1, 0]
by iterating over2n
elements.
- We effectively consider the array as
-
Iterating Through the Extended Array:
- Index 1:
current = colors[1 % 5] = 1
(Blue). Different fromcolors[0] = 0
(Red), so incrementcnt
to2
. - Index 2:
current = colors[2 % 5] = 0
(Red). Different fromcolors[1] = 1
(Blue), incrementcnt
to3
. - Index 3:
current = colors[3 % 5] = 1
(Blue). Different fromcolors[2] = 0
(Red), incrementcnt
to4
. - Index 4:
current = colors[4 % 5] = 0
(Red). Different fromcolors[3] = 1
(Blue), incrementcnt
to5
.
- Index 1:
-
Counting Alternating Groups:
- Since we have
cnt >= 3
ati = 3
andi = 4
, and the indexi
is greater thann
, incrementans
each time.
- Since we have
-
Final Output:
- By completion, we have found
ans = 3
alternating groups in the circle ([0, 1, 0]
,[1, 0, 1]
, and repeated[0, 1, 0]
when overlapping).
- By completion, we have found
Thus, this walkthrough demonstrates that the solution efficiently counts alternating groups while respecting the circular nature of the tile arrangement.
Solution Implementation
1from typing import List
2
3class Solution:
4 def numberOfAlternatingGroups(self, colors: List[int]) -> int:
5 k = 3 # Minimum number of consecutive different colors to form an alternating group
6 n = len(colors) # Length of the list of colors
7 ans = 0 # Counter for the number of alternating groups
8 cnt = 0 # Counter to track the length of the current alternating sequence
9
10 # Loop through the colors list twice to handle wraparound at the end
11 for i in range(2 * n):
12 # Check if the current color is the same as the previous one
13 if i > 0 and colors[i % n] == colors[(i - 1) % n]:
14 # Reset the counter if colors are the same
15 cnt = 1
16 else:
17 # Increment the counter if colors are different
18 cnt += 1
19
20 # Check if we have completed one full loop and the current sequence is at least 'k' long
21 if i >= n and cnt >= k:
22 ans += 1
23
24 return ans
25
1class Solution {
2 public int numberOfAlternatingGroups(int[] colors) {
3 int k = 3; // Minimum length of alternating group
4 int n = colors.length; // Length of colors array
5 int ans = 0; // Number of alternating groups
6 int count = 0; // Count of current alternating segment length
7
8 // Loop through twice the length of the array to handle cyclic behavior
9 for (int i = 0; i < n * 2; ++i) {
10 int currentColor = colors[i % n]; // Current color
11 int previousColor = colors[(i - 1) % n]; // Previous color
12
13 // Check if the current color equals the previous color
14 if (i > 0 && currentColor == previousColor) {
15 count = 1; // Reset count to 1 if the same color repeats
16 } else {
17 ++count; // Increment count for alternating sequence
18 }
19
20 // Check if we are past the first length of the array and the count is sufficient
21 if (i >= n && count >= k) {
22 ans++; // Increment the number of alternating groups
23 }
24 }
25
26 return ans; // Return the number of alternating groups found
27 }
28}
29
1#include <vector>
2
3class Solution {
4public:
5 int numberOfAlternatingGroups(std::vector<int>& colors) {
6 // Set the minimum length of alternating groups
7 int minLength = 3;
8
9 // Get the size of the input colors vector
10 int totalColors = colors.size();
11
12 // Initialize the count of alternating groups
13 int alternatingGroupCount = 0;
14
15 // Initialize the count of consecutive different colors
16 int currentCount = 0;
17
18 // Loop through the colors array twice to handle circular groups
19 for (int i = 0; i < totalColors * 2; ++i) {
20 // Use modulo to cycle through the colors
21 if (i > 0 && colors[i % totalColors] == colors[(i - 1) % totalColors]) {
22 // Reset the count if the current color is the same as the previous color
23 currentCount = 1;
24 } else {
25 // Increment the count for consecutive different colors
26 ++currentCount;
27 }
28 // Check if a valid alternating group is found when half the cycle is complete
29 if (i >= totalColors && currentCount >= minLength) {
30 // Increment the number of alternating groups
31 ++alternatingGroupCount;
32 }
33 }
34
35 // Return the total number of alternating groups
36 return alternatingGroupCount;
37 }
38};
39
1function numberOfAlternatingGroups(colors: number[]): number {
2 // Define the minimum length of the alternating sequence required
3 const k = 3;
4 // Get the total number of colors
5 const n = colors.length;
6 // Initialize the answer (number of groups) and a counter for consecutive different colors
7 let ans = 0;
8 let cnt = 0;
9
10 // Iterate over each color twice (simulate a circular array)
11 for (let i = 0; i < n * 2; ++i) {
12 // If the current and previous colors are the same, reset the counter
13 if (i > 0 && colors[i % n] === colors[(i - 1) % n]) {
14 cnt = 1;
15 } else {
16 // Otherwise, increment the counter
17 ++cnt;
18 }
19 // Once we're past the first round and have an alternating sequence of at least 'k' colors, increment the answer
20 if (i >= n && cnt >= k) {
21 ans++;
22 }
23 }
24 return ans;
25}
26
Time and Space Complexity
The time complexity is O(n)
because the loop iterates through the array colors
twice (due to n << 1
), but this still results in a linear relationship with respect to the length of the list. The constants in time complexity, such as multiplying by 2, do not affect the asymptotic complexity.
The space complexity is O(1)
because the solution only utilizes a fixed amount of additional space (for variables like k
, n
, ans
, and cnt
), regardless of the size of the input list colors
.
Learn more about how to find time and space complexity quickly.
Which of these pictures shows the visit order of a depth-first search?
Recommended Readings
https algomonster s3 us east 2 amazonaws com cover_photos stack svg Sliding Window Maximum Monotonic Stack We have an array and a sliding window defined by a start index and an end index The sliding window moves from left of the array to right There are always k elements in
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Want a Structured Path to Master System Design Too? Don’t Miss This!