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
indexwith the givencolor - 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
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)!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code