Number of Adjacent Elements With the Same Color - Problem

Imagine you're painting a fence with n sections, initially all unpainted (represented by 0). You'll receive a series of painting instructions, and after each instruction, you need to count how many adjacent pairs of sections have the same color.

You start with an array colors of length n where all elements are initially 0 (unpainted). You're given a 2D array queries where queries[i] = [index, color] represents:

  • Paint section index with the given color
  • Count all adjacent pairs that now have matching colors

Goal: Return an array where each element is the count of matching adjacent pairs after processing each query.

Example: If sections [1,2,2,1] exist, there's 1 matching pair: the middle two 2's are adjacent and identical.

Input & Output

example_1.py โ€” Basic Example
$ Input: n = 4, queries = [[0,2],[1,2],[3,1],[2,2]]
โ€บ Output: [0, 1, 1, 2]
๐Ÿ’ก Note: Initially colors = [0,0,0,0]. After [0,2]: [2,0,0,0] โ†’ 0 matches. After [1,2]: [2,2,0,0] โ†’ 1 match (positions 0,1). After [3,1]: [2,2,0,1] โ†’ 1 match. After [2,2]: [2,2,2,1] โ†’ 2 matches (positions 0,1 and 1,2).
example_2.py โ€” Single Element
$ Input: n = 1, queries = [[0,1]]
โ€บ Output: [0]
๐Ÿ’ก Note: With only one element, there are no adjacent pairs possible, so the answer is always 0.
example_3.py โ€” All Same Color
$ Input: n = 3, queries = [[0,1],[1,1],[2,1]]
โ€บ Output: [0, 1, 2]
๐Ÿ’ก Note: After [0,1]: [1,0,0] โ†’ 0 matches. After [1,1]: [1,1,0] โ†’ 1 match. After [2,1]: [1,1,1] โ†’ 2 matches (all adjacent pairs match).

Constraints

  • 1 โ‰ค n โ‰ค 105
  • 1 โ‰ค queries.length โ‰ค 105
  • queries[i].length == 2
  • 0 โ‰ค indexi < n
  • 1 โ‰ค colori โ‰ค 105
  • Adjacent pairs are only counted if both colors are non-zero

Visualization

Tap to expand
0220โœ“ Match Found!SmartInspectorO(1)Efficiency ComparisonโŒ Brute Force:โ€ข Check ALL pairs every timeโ€ข O(q ร— n) time complexityโ€ข Wasteful recalculationโœ… Optimal Solution:โ€ข Check only 2 neighborsโ€ข O(q) time complexityโ€ข Incremental updates๐Ÿš€ Up to 10,000x faster!
Understanding the Visualization
1
Initial Fence
Start with unpainted fence sections [0,0,0,0]
2
Paint Section
Paint section 1 with color 2: [0,2,0,0] โ†’ 0 matches
3
Paint Adjacent
Paint section 2 with color 2: [0,2,2,0] โ†’ 1 match found!
4
Efficient Checking
Only check neighbors of updated section for count changes
Key Takeaway
๐ŸŽฏ Key Insight: When painting one fence section, only its immediate neighbors matter for counting changes - this transforms an O(n) operation into O(1)!
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
23.6K Views
Medium Frequency
~15 min Avg. Time
894 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