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] == 0 means that tile i is red
  • colors[i] == 1 means that tile i is 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 size size_i
  • queries[i] = [2, index_i, color_i]: change colors[index_i] to color_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
Alternating Groups III: Circular Pattern Detectioncolors = [0,1,1,0,1], find alternating groups01101i=0i=1i=2i=3i=4Query [1,3]: Find alternating groups of size 3Groups: [1,0,1] at positions (2,3,4) and (3,4,0)Output: 2 alternating groups found
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
Asked in
Google 15 Meta 12 Amazon 8
3.2K Views
Medium Frequency
~35 min Avg. Time
145 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen