Skip to main content
Back to problems
#2672
Medium Algorithms

Number of adjacent elements with the same color

Array
58.1% acceptance
Feb 25, 2026
394
117
You are given an integer n representing an array colors of length n where all elements are set to 0's meaning uncolored. You are also given a 2D integer array queries where queries[i] = [indexi, colori]. For the ith query: Set colors[indexi] to colori. Count the number of adjacent pairs in colors which have the same color (regardless of colori). Return an array answer of the same length as queries where answer[i] is the answer to the ith query.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn color_the_array(n: i32, queries: Vec<Vec<i32>>) -> Vec<i32> {
    let n = n as usize;
    let mut colors = vec![0i32; n];
    let mut cnt = 0i32;
    let mut result = Vec::with_capacity(queries.len());
    for q in &queries {
      let idx = q[0] as usize;
      let col = q[1];
      // Remove old contributions
      if idx > 0 && colors[idx-1] != 0 && colors[idx-1] == colors[idx] { cnt -= 1; }
      if idx + 1 < n && colors[idx] != 0 && colors[idx] == colors[idx+1] { cnt -= 1; }
      colors[idx] = col;
      // Add new contributions
      if idx > 0 && colors[idx-1] == col { cnt += 1; }
      if idx + 1 < n && col == colors[idx+1] { cnt += 1; }
      result.push(cnt);
    }
    result
  }
}