Alternating Groups III - Problem
There are some red and blue tiles arranged in a circle. You are given an array of integers colors and a 2D array of integers queries.
The color of tile i is represented by colors[i]:
colors[i] == 0means that tileiis redcolors[i] == 1means that tileiis blue
An alternating group is a contiguous subset of tiles in the circle with alternating colors (each tile in the group except the first and last one has a different color from its adjacent tiles in the group).
You have to process queries of two types:
queries[i] = [1, size_i]: determine the count of alternating groups with sizesize_iqueries[i] = [2, index_i, color_i]: changecolors[index_i]tocolor_i
Return an array answer containing the results of the queries of the first type in order.
Note: Since colors represents a circle, the first and the last tiles are considered to be next to each other.
Input & Output
Example 1 — Basic Pattern Counting
$
Input:
colors = [0,1,1,0,1], queries = [[1,3],[2,1,0],[1,3]]
›
Output:
[2,2]
💡 Note:
First query [1,3] counts alternating groups of size 3. Groups [1,0,1] at positions (2,3,4) and (3,4,0) are valid. After updating index 1 to 0, we still have 2 groups of size 3.
Example 2 — Size 1 Groups
$
Input:
colors = [0,0,1,0], queries = [[1,4],[2,0,1],[1,4]]
›
Output:
[1,0]
💡 Note:
Initially only one alternating group of size 4 exists. After changing colors[0] to 1, no alternating groups of size 4 remain.
Example 3 — All Same Colors
$
Input:
colors = [0,0,0], queries = [[1,2]]
›
Output:
[0]
💡 Note:
No alternating groups of size 2 exist when all colors are the same.
Constraints
- 1 ≤ colors.length ≤ 5 × 104
- 0 ≤ colors[i] ≤ 1
- 1 ≤ queries.length ≤ 5 × 104
- queries[i][0] ∈ {1, 2}
- For type 1 queries: 1 ≤ size_i ≤ colors.length
- For type 2 queries: 0 ≤ index_i < colors.length, 0 ≤ color_i ≤ 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Circular array of colors [0,1,1,0,1] and queries
2
Pattern Detection
Find alternating groups of specified sizes
3
Dynamic Updates
Handle color changes and recount patterns
Key Takeaway
🎯 Key Insight: Efficiently track alternating segments in circular arrays and update only affected regions on color changes
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code