Problem Description
Given an integer n representing the length of an array colors (initialized with zeros, meaning uncolored) and a list of queries where each query provides an index and a new color, update the array at the specified index with the new color. After each query, count the number of adjacent pairs in the array that have the same color. Return an array where each element is the count after processing the respective query.
Key Insights
- The initial array is uncolored (all zeros); we only start counting adjacent pairs when elements are colored (non-zero).
- A brute-force recount of adjacent pairs after each query would be inefficient for large n and many queries.
- Instead, maintain a running count of adjacent matching pairs.
- For each query, only the pairs involving the updated index might change — check the left neighbor and the right neighbor.
- Before updating, subtract the contribution of the current color (if any) with its neighbors, then update the color and add the new contributions.
- This allows each query to be processed in constant time.
Space and Time Complexity
Time Complexity: O(1) per query, resulting in O(q) overall where q is the number of queries. Space Complexity: O(n) for storing the colors array.
Solution
We maintain an array (or list) called colors to track the current color of each element. Also, keep a variable count to store the current number of adjacent pairs with the same color.
For each query:
- Read the index and the new color.
- Check the element's left neighbor (if exists):
- If the previous color at index and its left neighbor matched, decrement the count.
- Check the element's right neighbor (if exists):
- If the previous color at index and its right neighbor matched, decrement the count.
- Update the value at the specified index.
- Again, check the updated index’s left neighbor:
- If the new color matches with the left neighbor, increment the count.
- Similarly, check the right neighbor:
- If the new color matches with the right neighbor, increment the count.
- Append the current count to the result after processing the query.
This method uses local adjustments to the count based on the neighbors and processes each query in constant time while using O(n) additional space for the colors array.