Number of Adjacent Elements With the Same Color — LeetCode 2672 Python Solution

MediumArray
Problem
#2672
Reading time
3 min

The problem

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] = [indexi, colori].

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 2672. Number of Adjacent Elements With the Same Color?
LeetCode 2672. Number of Adjacent Elements With the Same Color is rated Medium on LeetCode.
What topics does LeetCode 2672. Number of Adjacent Elements With the Same Color cover?
LeetCode 2672. Number of Adjacent Elements With the Same Color is tagged Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview