Number of Adjacent Elements With the Same Color — LeetCode 2672 Python Solution
MediumArray
- Problem
- #2672
- Reading time
- 3 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.