MediumNo. 2672
Number of Adjacent Elements With the Same Color — LeetCode 2672 Python Solution
- Topics
- Array
- 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
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
- Time
- O(n)
- Space · auxiliary
- O(1) to O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0057 | Insert Interval | Medium |
| 0228 | Summary Ranges | Easy |
| 0485 | Max Consecutive Ones | Easy |
| 0665 | Non-decreasing Array | Medium |
| 0674 | Longest Continuous Increasing Subsequence | Easy |
| 0699 | Falling Squares | Hard |
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.