Shortest Distance to Target Color Problem
Description
LeetCode Problem 1182.
You are given an array colors, in which there are three colors: 1, 2 and 3.
You are also given some queries. Each query consists of two integers i and c, return the shortest distance between the given index i and the target color c. If there is no solution return -1.
Example 1:
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).
The nearest 2 from index 2 is at index 2 itself (0 steps away).
The nearest 1 from index 6 is at index 3 (3 steps away).
Example 2:
Input: colors = [1,2], queries = [[0,3]]
Output: [-1]
Explanation: There is no 3 in the array.
Constraints:
1 <= colors.length <= 5*10^41 <= colors[i] <= 31 <= queries.length <= 5*10^4queries[i].length == 20 <= queries[i][0] < colors.length1 <= queries[i][1] <= 3
Solution
Approach: Precompute the Nearest Color in Both Directions
Answering each query by walking left and right from i costs O(n) per query, too slow for 5 * 104 of each. But there are only three colors, so we can precompute, for every index and every color, the distance to the nearest index with that color.
The nearest c is either the closest one at or to the left of i, or the closest one at or to the right. Two passes find both:
- Left to right, remember the last index where each color appeared. The left distance is
i - last[c]. - Right to left, do the same and keep the smaller of the two distances.
If a color has not been seen yet, start its "last index" at minus infinity (or plus infinity for the right-to-left pass), so its distance is huge. A distance larger than n therefore means the color is not in the array at all, and the query's answer is -1. With integers, use a large value such as 230 instead of infinity so that subtracting an index cannot overflow.
Complexity: O(n + q) time and O(n) space for the three distance arrays, where q is the number of queries.
class Solution:
def shortestDistanceColor(self, colors: List[int], queries: List[List[int]]) -> List[int]:
n = len(colors)
INF = float("inf")
# dist[c][i]: distance from index i to the nearest color c (INF if c never appears).
dist = [[INF] * n for _ in range(4)]
last = [-INF] * 4 # index of the latest color c seen so far, left to right
for i, c in enumerate(colors):
last[c] = i
for color in (1, 2, 3):
dist[color][i] = i - last[color]
last = [INF] * 4 # now right to left
for i in range(n - 1, -1, -1):
last[colors[i]] = i
for color in (1, 2, 3):
dist[color][i] = min(dist[color][i], last[color] - i)
return [-1 if dist[c][i] == INF else dist[c][i] for i, c in queries]