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.
💡 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.
The key insight is to efficiently track alternating color patterns in a circular array while handling dynamic updates. The optimal approach uses segment tracking to pre-compute alternating lengths and update only affected regions. Time: O(Q × N), Space: O(N)
Common Approaches
✓
Brute Force
⏱️ Time: O(Q × N × S)
Space: O(1)
For type 1 queries, iterate through all possible starting positions and check if each substring of the required size forms an alternating pattern. For type 2 queries, simply update the color at the given index.
Segment Tracking
⏱️ Time: O(Q × N)
Space: O(N)
Pre-compute the length of alternating segments starting from each position. For count queries, use these precomputed lengths. For update queries, only recompute segments affected by the color change.
Brute Force — Algorithm Steps
Process each query sequentially
For count queries: check all positions for alternating patterns of given size
For update queries: change the color at specified index
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Query Processing
Process each query sequentially
2
Pattern Checking
For count queries, check all positions
3
Color Updates
For update queries, change color directly
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int colors[50000];
static int queries[50000][3];
static int result[50000];
int countAlternatingGroups(int* colors, int n, int size) {
if (size == 1) return n;
if (size > n) return 0;
int count = 0;
for (int start = 0; start < n; start++) {
int isAlternating = 1;
for (int i = 1; i < size; i++) {
int pos = (start + i) % n;
int prevPos = (start + i - 1) % n;
if (colors[pos] == colors[prevPos]) {
isAlternating = 0;
break;
}
}
if (isAlternating) count++;
}
return count;
}
int* solution(int* colors, int colorsSize, int queries[][3], int queriesSize, int* queriesColSize, int* returnSize) {
int resultIndex = 0;
int colorsCopy[50000];
for (int i = 0; i < colorsSize; i++) {
colorsCopy[i] = colors[i];
}
for (int i = 0; i < queriesSize; i++) {
if (queries[i][0] == 1) {
result[resultIndex++] = countAlternatingGroups(colorsCopy, colorsSize, queries[i][1]);
} else {
colorsCopy[queries[i][1]] = queries[i][2];
}
}
*returnSize = resultIndex;
return result;
}
int parseColors(char* line, int* colors) {
int count = 0;
char* ptr = line + 1; // Skip '['
while (*ptr && *ptr != ']') {
while (*ptr == ' ' || *ptr == ',') ptr++;
if (*ptr >= '0' && *ptr <= '9') {
colors[count++] = strtol(ptr, &ptr, 10);
} else {
ptr++;
}
}
return count;
}
int parseQueries(char* line, int queries[][3]) {
int count = 0;
char* ptr = line + 2; // Skip "[["
while (*ptr && count < 50000) {
int querySize = 0;
// Parse one query
while (*ptr && *ptr != ']' && querySize < 3) {
while (*ptr == ' ' || *ptr == ',' || *ptr == '[') ptr++;
if (*ptr >= '0' && *ptr <= '9') {
queries[count][querySize++] = strtol(ptr, &ptr, 10);
} else {
ptr++;
}
}
if (querySize > 0) count++;
// Skip to next query
while (*ptr && *ptr != '[' && *ptr != '\n' && *ptr != '\0') ptr++;
if (*ptr == '[') ptr++;
if (*ptr == '\n' || *ptr == '\0') break;
}
return count;
}
int main() {
char line[100000];
// Read colors
fgets(line, sizeof(line), stdin);
int colorsSize = parseColors(line, colors);
// Read queries
fgets(line, sizeof(line), stdin);
int dummy[50000];
int queriesSize = parseQueries(line, queries);
int returnSize;
int* res = solution(colors, colorsSize, queries, queriesSize, dummy, &returnSize);
printf("[");
for (int i = 0; i < returnSize; i++) {
printf("%d", res[i]);
if (i < returnSize - 1) printf(",");
}
printf("]\n");
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(Q × N × S)
Q queries, each count query checks N positions with up to S comparisons
n
2n
✓ Linear Growth
Space Complexity
O(1)
Only using variables for iteration, no extra data structures
n
2n
✓ Linear Space
3.3K Views
MediumFrequency
~35 minAvg. Time
145 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.