Leetcode: Number of Adjacent Elements With the Same Color

Yuqiu Ge
1 min readMay 7, 2023

Problem: https://leetcode.com/contest/weekly-contest-344/problems/number-of-adjacent-elements-with-the-same-color/

Idea: simple and easy to understand, every time we change the color, we check (at most) 2 adjacent elements, if we are destroying the same color combination or if we are adding some additional ones. Of course pay attention to the exact front and the back of the array.

int[] colorTheArray(int n, int[][] queries) {
int L = queries.length;
int[] result = new int[L];
int[] colors = new int[n];

int sameColor = 0;
for (int i = 0; i < L; i++) {
int index = queries[i][0];
int color = queries[i][1];

if (index-1 >= 0 && colors[index-1] > 0) {
if (colors[index-1] == colors[index] && colors[index-1] != color) {
sameColor--;
} else if (colors[index-1] != colors[index] && colors[index-1] == color) {
sameColor++;
}
}
if (index+1 < n && colors[index+1] > 0) {
if (colors[index+1] == colors[index] && colors[index+1] != color) {
sameColor--;
} else if (colors[index+1] != colors[index] && colors[index+1] == color) {
sameColor++;
}
}
result[i] = sameColor;
colors[index] = color;
}

return result;
}

--

--