#3245
Alternating Groups III
HardArrayBinary Indexed TreeOrdered SetHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can preprocess the colors to find maximal alternating groups and store their sizes. This allows us to quickly answer queries about group sizes without rechecking the entire array.
⚙️
Algorithm
3 steps- 1Step 1: Preprocess the colors array to find all maximal alternating groups and their sizes.
- 2Step 2: Store the sizes of these groups in a frequency map for quick lookup.
- 3Step 3: For type 1 queries, simply return the count from the frequency map. For type 2 queries, update the colors and adjust the groups as necessary.
solution.py26 lines
1from collections import defaultdict
2
3def count_alternating_groups(colors, queries):
4 n = len(colors)
5 group_sizes = defaultdict(int)
6 def update_groups():
7 count = 0
8 size = 1
9 for i in range(n):
10 if colors[i] != colors[(i + 1) % n]:
11 size += 1
12 else:
13 if size > 1:
14 group_sizes[size] += 1
15 size = 1
16 if size > 1:
17 group_sizes[size] += 1
18 update_groups()
19 results = []
20 for query in queries:
21 if query[0] == 1:
22 results.append(group_sizes[query[1]])
23 elif query[0] == 2:
24 colors[query[1]] = query[2]
25 update_groups()
26 return resultsℹ
Complexity note: The complexity is O(n) for preprocessing the groups and O(1) for each query, making it efficient for large inputs.
- 1Understanding the circular nature of the array is crucial.
- 2Efficiently managing updates to the colors is key to optimizing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.