2672. Number of Adjacent Elements With the Same Color | 1705
Straightforward coding.
1class Solution:
2 def colorTheArray(self, n: int, queries: List[List[int]]) -> List[int]:
3 # e.g. when changing index i to new:
4 # check arr[i], store it old
5 # check if arr[i-1] == old: pair -= 1
6 # else if arr[i-1] == new: pair += 1
7 # check if arr[i+1] == old: pair -= 1
8 # else if arr[i+1] == new: pair += 1
9 # also we don't care about uncolored.
10 # also if old == new we just do nothing
11
12 arr = [0] * n
13 result = [0]
14
15 for i, new_v in queries:
16 pair_delta = 0
17 old_v = arr[i]
18
19 if old_v != new_v:
20 if i - 1 > -1 and arr[i - 1] != 0:
21 if arr[i - 1] == old_v:
22 pair_delta -= 1
23 elif arr[i - 1] == new_v:
24 pair_delta += 1
25 if i + 1 < n and arr[i + 1] != 0:
26 if arr[i + 1] == old_v:
27 pair_delta -= 1
28 elif arr[i + 1] == new_v:
29 pair_delta += 1
30 arr[i] = new_v
31
32 result.append(result[-1] + pair_delta)
33
34 return result[1:]