Number of Adjacent Elements With the Same Color Problem
#2672
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2672.
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] = [index_i, color_i]. For the i^th query:
- Set
colors[index_i]tocolor_i. - Count the number of adjacent pairs in
colorswhich have the same color (regardless ofcolor_i).
Return an array answer of the same length as queries where answer[i] is the answer to the i^th query.
Example 1:
Input: n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]]
Output: [0,1,1,0,2]
Explanation:
- Initially array colors = [0,0,0,0], where 0 denotes uncolored elements of the array.
- After the 1^st query colors = [2,0,0,0]. The count of adjacent pairs with the same color is 0.
- After the 2^nd query colors = [2,2,0,0]. The count of adjacent pairs with the same color is 1.
- After the 3^rd query colors = [2,2,0,1]. The count of adjacent pairs with the same color is 1.
- After the 4^th query colors = [2,1,0,1]. The count of adjacent pairs with the same color is 0.
- After the 5^th query colors = [2,1,1,1]. The count of adjacent pairs with the same color is 2.
Example 2:
Input: n = 1, queries = [[0,100000]]
Output: [0]
Explanation:
After the 1^st query colors = [100000]. The count of adjacent pairs with the same color is 0.
Constraints:
1 <= n <= 10^51 <= queries.length <= 10^5queries[i].length == 20 <= index_i <= n - 11 <= color_i <= 10^5
Solution
Approach: Update only the neighbours
A query changes one cell, so only the pairs it forms with its two neighbours can change. Keep the current count x of equal adjacent pairs.
For a query (i, c):
- If cell
iis already coloured, subtract each neighbour that has the same old colour. - Add each neighbour whose colour equals
c. - Record
xand storecati.
Cells with colour 0 are uncoloured and never count.
Complexity: time O(n + q), space O(n), where q is the number of queries.
class Solution:
def colorTheArray(self, n: int, queries: List[List[int]]) -> List[int]:
nums = [0] * n
ans = [0] * len(queries)
x = 0
for k, (i, c) in enumerate(queries):
if i > 0 and nums[i] and nums[i - 1] == nums[i]:
x -= 1
if i < n - 1 and nums[i] and nums[i + 1] == nums[i]:
x -= 1
if i > 0 and nums[i - 1] == c:
x += 1
if i < n - 1 and nums[i + 1] == c:
x += 1
ans[k] = x
nums[i] = c
return ans