[LeetCode] Number of Adjacent Elements With the Same Color

2672. Number of Adjacent Elements With the Same Color

There is a 0-indexed array nums of length n. Initially, all elements are uncolored (has a value of 0).

You are given a 2D integer array queries where queries[i] = [indexi, colori].

For each query, you color the index indexi with the color colori in the array nums.

Return an array answer of the same length as queries where answer[i] is the number of adjacent elements with the same color after the ith query.

More formally, answer[i] is the number of indices j, such that 0 <= j < n - 1 and nums[j] == nums[j + 1] and nums[j] != 0 after the ith query.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
vector<int> colorTheArray(int n, vector<vector<int>>& queries) {
vector<int> C(n+2);
vector<int> res;
auto good = [&](int idx) {
int res = 0;
if(C[idx-1] and C[idx] and C[idx-1] == C[idx]) res += 1;
if(C[idx+1] and C[idx] and C[idx+1] == C[idx]) res += 1;
return res;
};
int now = 0;
for(auto q : queries) {
int idx = q[0] + 1, c = q[1];
now -= good(idx);
C[idx] = c;
now += good(idx);
res.push_back(now);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/07/PS/LeetCode/number-of-adjacent-elements-with-the-same-color/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.