This problem asks to find the shortest distance from a given index i
in the colors
array to the target color c
. The solution uses a pre-processing technique to significantly improve efficiency.
The core idea is to avoid repeatedly searching for the nearest color for each query. Instead, we precompute the distances to the nearest occurrence of each color (1, 2, and 3) from every index in both directions (left and right).
Preprocessing:
left
and right
, are created. left[i][j]
stores the index of the nearest occurrence of color j+1
to the left of index i
(inclusive). Similarly, right[i][j]
stores the index of the nearest occurrence of color j+1
to the right of index i
(inclusive).-∞
and ∞
are used as placeholders respectively. These are represented as a sufficiently large negative and positive number in the code (e.g., -inf
and inf
).colors
once in each direction to populate left
and right
.Query Processing:
[i, c]
, the shortest distance is determined by:
min(i - left[i + 1][c - 1], right[i][c - 1] - i)
left[i+1][c-1]
is used because it considers indices before i
.right[i][c-1]
is used directly as it represents distances from index i
to the right.d
exceeds the length of colors
, it means the target color c
is not present, so -1 is returned for that query.colors
and Q is the number of queries. The preprocessing step takes O(N) time, and processing each query takes O(1) time, resulting in O(Q) for all queries.left
and right
arrays.The code examples provided earlier demonstrate the implementation of this approach in different programming languages. Each example follows the same algorithm:
left
and right
arrays and initialize them with appropriate placeholders.colors
to populate left
and right
with distances to nearest occurrences of each color.This preprocessing approach transforms the problem from multiple linear searches (which would have O(N*Q) time complexity) into a constant-time query operation, resulting in a much more efficient solution.