LeetCode-in-Java

2672. Number of Adjacent Elements With the Same Color

Medium

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.

Example 1:

Input: n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]]

Output: [0,1,1,0,2]

Explanation: Initially array nums = [0,0,0,0], where 0 denotes uncolored elements of the array.

Example 2:

Input: n = 1, queries = [[0,100000]]

Output: [0]

Explanation: Initially array nums = [0], where 0 denotes uncolored elements of the array.

Constraints:

Solution

public class Solution {
    public int[] colorTheArray(int n, int[][] q) {
        if (n == 1) {
            return new int[q.length];
        }
        int[] ans = new int[q.length];
        int[] color = new int[n];
        int cnt = 0;
        for (int i = 0; i < q.length; i++) {
            int ind = q[i][0];
            int assColor = q[i][1];
            int leftColor = 0;
            int rytColor = 0;
            if (ind - 1 >= 0) {
                leftColor = color[ind - 1];
            }
            if (ind + 1 < n) {
                rytColor = color[ind + 1];
            }
            if (color[ind] != 0 && leftColor == color[ind]) {
                cnt--;
            }
            if (color[ind] != 0 && rytColor == color[ind]) {
                cnt--;
            }
            color[ind] = assColor;
            if (color[ind] != 0 && leftColor == color[ind]) {
                cnt++;
            }
            if (color[ind] != 0 && rytColor == color[ind]) {
                cnt++;
            }
            ans[i] = cnt;
        }
        return ans;
    }
}