#2672
Number of Adjacent Elements With the Same Color
MediumArrayHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of counting adjacent pairs from scratch after each query, we can keep track of only the affected pairs (the pairs adjacent to the changed index). This reduces unnecessary computations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an array colors of size n and a variable to keep track of the number of adjacent pairs.
- 2Step 2: For each query, check the colors of the neighboring elements before and after the update to adjust the count of adjacent pairs.
- 3Step 3: Update the color and append the current count to the result.
solution.py16 lines
1def countAdjacentPairs(n, queries):
2 colors = [0] * n
3 count = 0
4 result = []
5 for index, color in queries:
6 if index > 0 and colors[index] == colors[index - 1]:
7 count -= 1
8 if index < n - 1 and colors[index] == colors[index + 1]:
9 count -= 1
10 colors[index] = color
11 if index > 0 and colors[index] == colors[index - 1]:
12 count += 1
13 if index < n - 1 and colors[index] == colors[index + 1]:
14 count += 1
15 result.append(count)
16 return resultℹ
Complexity note: This complexity is efficient because we only check the affected neighbors (up to 2) for each query, leading to a linear time complexity overall.
- 1Only the neighbors of the modified index need to be checked for adjacent pairs.
- 2Keeping track of the count allows for efficient updates rather than recalculating from scratch.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.