Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2672. Number of Adjacent Elements With the Same Color

Array

Explanation:

To solve this problem, we need to iterate through the queries, update the colors array according to each query, and then count the adjacent elements with the same color.

We can achieve this by maintaining a count of adjacent elements with the same color while updating the colors array. For each query, we update the colors array and check if the adjacent elements have the same color. If they do, we increment the count.

Algorithm:

  1. Initialize an array colors of length n filled with zeros.
  2. Initialize a variable count to store the count of adjacent elements with the same color.
  3. Iterate through each query:
    • Update the colors array with the specified color at the given index.
    • Update the count by checking the adjacent elements in the colors array.
    • Store the current count in the result array.
  4. Return the result array.

Time Complexity: O(N) where N is the number of queries. Space Complexity: O(N) for the colors array and result array.

class Solution {
    public int[] numColor(int n, int[][] queries) {
        int[] colors = new int[n];
        int[] result = new int[queries.length];
        int count = 0;
        
        for (int i = 0; i < queries.length; i++) {
            int index = queries[i][0];
            int color = queries[i][1];
            
            colors[index] = color;
            
            if (index > 0 && colors[index - 1] == color) {
                count++;
            }
            if (index < n - 1 && colors[index + 1] == color) {
                count++;
            }
            
            result[i] = count;
        }
        
        return result;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.