Problem
You are given an integer n
representing an array colors
of length n
where all elements are set to 0’s meaning uncolored. You are also given a 2D integer array queries
where queries[i] = [indexi, colori]
. For the
ith
query :
- Set
colors[indexi]
tocolori
. - Count adjacent pairs in
colors
set to the same color (regardless ofcolori
).
Return an array answer
of the same length as queries
where answer[i]
is the answer to the ith
query.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= n <= 10^5
1 <= queries.length <= 10^5
queries[i].length == 2
0 <= indexi <= n - 1
1 <= colori <= 10^5
Solution
Method 1 -
Intuition
We need to efficiently track the number of adjacent pairs with the same color after each query. Since only one element changes per query, we can update the count by checking the affected neighbors before and after the change.
Approach
For each query, before updating, check if the left/right neighbor forms a same-color pair with the current index and subtract from the count if so. After updating, check again and add to the count if a new pair is formed. This way, we avoid recomputing the entire array each time.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(q)
where q = number of queries (each query is processed in O(1)). - 🧺 Space complexity:
O(n)
for the colors array.