You're working with a colorful array where each position contains one of three colors: 1 (red), 2 (green), or 3 (blue). Your task is to efficiently answer multiple queries about finding the shortest distance from any given position to the nearest occurrence of a specific target color.
For each query (i, c), you need to find the minimum number of steps required to reach color c from index i. If the target color doesn't exist in the array, return -1.
Example: Given colors = [1,1,2,1,3,2,2,3,3], if you're at index 3 (color 1) and looking for color 2, you can go left to index 2 (distance = 1) or right to index 5 (distance = 2), so the answer is 1.
Input & Output
Visualization
Time & Space Complexity
O(n) for preprocessing with DP, then O(1) per query
DP table storing distances for each position and color
Constraints
-
1 β€ colors.length β€ 5 Γ 104 -
1 β€ colors[i] β€ 3 -
1 β€ queries.length β€ 5 Γ 104 -
0 β€ queries[i][0] < colors.length -
1 β€ queries[i][1] β€ 3