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:
[3,3]
💡 Note:
First query [1,3] counts alternating groups of size 3. Groups starting at positions 2: [1,0,1], position 3: [0,1,0], and position 4: [1,0,0] are valid, giving 3 total. After updating index 1 to 0, colors becomes [0,0,1,0,1]. Groups of size 3 starting at positions 1: [0,1,0], position 2: [1,0,1], and position 3: [0,1,0] are valid, giving 3 total.
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code