Number of Adjacent Elements With the Same Color - Problem

You are given an integer n representing an array colors of length n where all elements are initially set to 0 (uncolored).

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

For each query:

  • Set colors[indexi] to colori
  • Count the number of adjacent pairs in the array that have the same color

Return an array answer where answer[i] is the count of same-colored adjacent pairs after the i-th query.

Input & Output

Example 1 — Basic Color Updates
$ Input: n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]]
Output: [0,1,1,0,2]
💡 Note: Initially [0,0,0,0]. After [0,2]: [2,0,0,0] → 0 pairs. After [1,2]: [2,2,0,0] → 1 pair (2,2). After [3,1]: [2,2,0,1] → 1 pair. After [1,1]: [2,1,0,1] → 0 pairs. After [2,1]: [2,1,1,1] → 2 pairs.
Example 2 — Single Element
$ Input: n = 1, queries = [[0,1]]
Output: [0]
💡 Note: Array [1] has no adjacent pairs, so count is 0.
Example 3 — No Adjacent Matches
$ Input: n = 3, queries = [[0,1],[1,2],[2,3]]
Output: [0,0,0]
💡 Note: Array becomes [1,2,3] with no adjacent elements having the same color.

Constraints

  • 1 ≤ n ≤ 105
  • 1 ≤ queries.length ≤ 105
  • queries[i].length == 2
  • 0 ≤ indexi < n
  • 1 ≤ colori ≤ 105

Visualization

Tap to expand
Adjacent Elements With Same Color INPUT Initial colors array (n=4): 0 [0] 0 [1] 0 [2] 0 [3] Queries: [0,2] - Set idx 0 to color 2 [1,2] - Set idx 1 to color 2 [3,1] - Set idx 3 to color 1 [1,1] - Set idx 1 to color 1 [2,1] - Set idx 2 to color 1 Note: 0 = uncolored (no matches) Only non-zero colors can match ALGORITHM STEPS 1 Initialize count=0, array of zeros 2 Before Update Check old matches at i-1, i+1 3 Apply Color Set colors[idx] = new color 4 After Update Check new matches, store count Trace: [2,0,0,0] count=0 [2,2,0,0] count=1 (0-1 match) [2,2,0,1] count=1 [2,1,0,1] count=0 (broke 0-1) [2,1,1,1] count=2 (1-2,2-3) 2 1 1 1 2 matches FINAL RESULT Answer array: 0 1 1 0 2 Query 1: [0,2] --> 0 matches Query 2: [1,2] --> 1 match Query 3: [3,1] --> 1 match Query 4: [1,1] --> 0 matches Query 5: [2,1] --> 2 matches Final Array State: 2 1 1 1 OK - Done! Key Insight: Smart Update: Instead of counting all adjacent pairs after each query (O(n) per query), we only check the neighbors at index i-1 and i+1. Subtract old matches before update, add new matches after. This gives O(1) per query. Remember: 0 (uncolored) never matches! TutorialsPoint - Number of Adjacent Elements With the Same Color | Smart Update Approach
Asked in
Google 25 Microsoft 18 Amazon 15
28.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen