Shortest Distance to Target Color — LeetCode 1182 Python Solution
MediumLeetCode PremiumArrayBinary SearchDynamic Programming
- Problem
- #1182
- Pattern
- Monotonic Stack
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are given an array colors, in which there are three colors: 1, 2 and 3. You are also given some queries.
Example
- Input
- colors = [1,1,2,1,3,2,2,3,3], queries = [[1,3],[2,2],[6,1]]
- Output
- [3,0,3]
- Explanation
- The nearest 3 from index 1 is at index 4 (3 steps away).
Python solution
Python
class Solution:
def shortestDistanceColor(
self, colors: List[int], queries: List[List[int]]
) -> List[int]:
n = len(colors)
right = [[inf] * 3 for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
for j in range(3):
right[i][j] = right[i + 1][j]
right[i][colors[i] - 1] = i
left = [[-inf] * 3 for _ in range(n + 1)]
for i, c in enumerate(colors, 1):
for j in range(3):
left[i][j] = left[i - 1][j]
left[i][c - 1] = i - 1
ans = []
for i, c in queries:
d = min(i - left[i + 1][c - 1], right[i][c - 1] - i)
ans.append(-1 if d > n else d)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 1182. Shortest Distance to Target Color is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1182. Shortest Distance to Target Color?
- LeetCode 1182. Shortest Distance to Target Color is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1182. Shortest Distance to Target Color?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1182. Shortest Distance to Target Color?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1182. Shortest Distance to Target Color cover?
- LeetCode 1182. Shortest Distance to Target Color is tagged Array, Binary Search and Dynamic Programming on LeetCode.
- Is LeetCode 1182. Shortest Distance to Target Color a premium problem?
- Yes. LeetCode 1182. Shortest Distance to Target Color is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.