LeetCode #3245 — HARD

Alternating Groups III

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

There are some red and blue tiles arranged circularly. You are given an array of integers colors and a 2D integers array 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, sizei], determine the count of alternating groups with size sizei.
  • queries[i] = [2, indexi, colori], change colors[indexi] to colori.

Return an array answer containing the results of the queries of the first type in order.

Note that since colors represents a circle, the first and the last tiles are considered to be next to each other.

Example 1:

Input: colors = [0,1,1,0,1], queries = [[2,1,0],[1,4]]

Output: [2]

Explanation:

First query:

Change colors[1] to 0.

Second query:

Count of the alternating groups with size 4:

Example 2:

Input: colors = [0,0,1,0,1,1], queries = [[1,3],[2,3,0],[1,5]]

Output: [2,0]

Explanation:

First query:

Count of the alternating groups with size 3:

Second query: colors will not change.

Third query: There is no alternating group with size 5.

Constraints:

  • 4 <= colors.length <= 5 * 104
  • 0 <= colors[i] <= 1
  • 1 <= queries.length <= 5 * 104
  • queries[i][0] == 1 or queries[i][0] == 2
  • For all i that:
    • queries[i][0] == 1: queries[i].length == 2, 3 <= queries[i][1] <= colors.length - 1
    • queries[i][0] == 2: queries[i].length == 3, 0 <= queries[i][1] <= colors.length - 1, 0 <= queries[i][2] <= 1
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: There are some red and blue tiles arranged circularly. You are given an array of integers colors and a 2D integers array 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, sizei], determine the count of alternating groups with size sizei. queries[i] = [2, indexi, colori], change colors[indexi] to colori. Return an array answer containing the results of the queries of the first type in order. Note that since colors represents a circle, the first and the last tiles are considered to be next to each other.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Segment Tree

Example 1

[0,1,1,0,1]
[[2,1,0],[1,4]]

Example 2

[0,0,1,0,1,1]
[[1,3],[2,3,0],[1,5]]
Step 02

Core Insight

What unlocks the optimal approach

  • Try using a segment tree to store the maximal alternating groups.
  • Store the sizes of these maximal alternating groups in another data structure.
  • Find the count of the alternating groups of size <code>k</code> with having the count of maximal alternating groups with size greater than or equal to <code>k</code> and the sum of their sizes.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3245: Alternating Groups III
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3245: Alternating Groups III
// package main
// 
// import "github.com/emirpasic/gods/v2/trees/redblacktree"
// 
// // https://space.bilibili.com/206214
// type fenwickTree [][2]int
// 
// // op=1,添加一个 size
// // op=-1,移除一个 size
// func (t fenwickTree) update(size, op int) {
// 	for i := len(t) - size; i < len(t); i += i & -i {
// 		t[i][0] += op
// 		t[i][1] += op * size
// 	}
// }
// 
// // 返回 >= size 的元素个数,元素和
// func (t fenwickTree) query(size int) (cnt, sum int) {
// 	for i := len(t) - size; i > 0; i &= i - 1 {
// 		cnt += t[i][0]
// 		sum += t[i][1]
// 	}
// 	return
// }
// 
// func numberOfAlternatingGroups(a []int, queries [][]int) (ans []int) {
// 	n := len(a)
// 	set := redblacktree.New[int, struct{}]()
// 	t := make(fenwickTree, n+1)
// 
// 	// op=1,添加一个结束位置 i
// 	// op=-1,移除一个结束位置 i
// 	update := func(i, op int) {
// 		prev, ok := set.Floor(i)
// 		if !ok {
// 			prev = set.Right()
// 		}
// 		pre := prev.Key
// 
// 		next, ok := set.Ceiling(i)
// 		if !ok {
// 			next = set.Left()
// 		}
// 		nxt := next.Key
// 
// 		t.update((nxt-pre+n-1)%n+1, -op) // 移除/添加旧长度
// 		t.update((i-pre+n)%n, op)
// 		t.update((nxt-i+n)%n, op) // 添加/移除新长度
// 	}
// 
// 	// 添加一个结束位置 i
// 	add := func(i int) {
// 		if set.Empty() {
// 			t.update(n, 1)
// 		} else {
// 			update(i, 1)
// 		}
// 		set.Put(i, struct{}{})
// 	}
// 
// 	// 移除一个结束位置 i
// 	del := func(i int) {
// 		set.Remove(i)
// 		if set.Empty() {
// 			t.update(n, -1)
// 		} else {
// 			update(i, -1)
// 		}
// 	}
// 
// 	for i, c := range a {
// 		if c == a[(i+1)%n] {
// 			add(i) // i 是一个结束位置
// 		}
// 	}
// 	for _, q := range queries {
// 		if q[0] == 1 {
// 			if set.Empty() {
// 				ans = append(ans, n) // 每个长为 size 的子数组都符合要求
// 			} else {
// 				cnt, sum := t.query(q[1])
// 				ans = append(ans, sum-cnt*(q[1]-1))
// 			}
// 		} else {
// 			i := q[1]
// 			if a[i] == q[2] { // 无影响
// 				continue
// 			}
// 			pre, nxt := (i-1+n)%n, (i+1)%n
// 			// 修改前,先去掉结束位置
// 			if a[pre] == a[i] {
// 				del(pre)
// 			}
// 			if a[i] == a[nxt] {
// 				del(i)
// 			}
// 			a[i] ^= 1
// 			// 修改后,添加新的结束位置
// 			if a[pre] == a[i] {
// 				add(pre)
// 			}
// 			if a[i] == a[nxt] {
// 				add(i)
// 			}
// 		}
// 	}
// 	return
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n + q log n)
Space
O(n)

Approach Breakdown

BRUTE FORCE
O(n × q) time
O(1) space

For each of q queries, scan the entire range to compute the aggregate (sum, min, max). Each range scan takes up to O(n) for a full-array query. With q queries: O(n × q) total. Point updates are O(1) but queries dominate.

SEGMENT TREE
O(n + q log n) time
O(n) space

Building the tree is O(n). Each query or update traverses O(log n) nodes (tree height). For q queries: O(n + q log n) total. Space is O(4n) ≈ O(n) for the tree array. Lazy propagation adds O(1) per node for deferred updates.

Shortcut: Build O(n), query/update O(log n) each. When you need both range queries AND point updates.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.