![]() |
VOOZH | about |
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.
Examples:
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).Input: colors = [2, 1, 1, 3, 2, 3, 1, 3, 3] queries = [[1, 2], [5, 3], [7, 1]]
Output: [1, 0, 1]Explanation: The nearest 2 from index 1 is at index 0 (1 steps away). The nearest 3 from index 5 is at index 5 itself (0 steps away). The nearest 1 from index 7 is at index 6 (1 steps away).
Approach: To solve the problem, follow the below idea:
The problem can be solved by precomputation the minimum distance to the colors 1, 2 and 3 on the right as well as on the left. For each index i, we can store the minimum distance of color 1, 2 and 3 on the right and on the left and return the minimum between them. We can maintain 2 2D arrays of size N * 3, left[][] and right[][] such that left[i][j] stores the nearest index with color j + 1 on the left of index i(including i) and right[i][j] stores the nearest index with color j + 1 to the right of index i(including index i).
Step-by-step algorithm:
Copy the values from the previous indices, left[i][j] = left[i - 1][j]left[i][color[i] - 1] = i;Copy the values from the next indices, right[i][j] = right[i + 1][j][i][color[i] - 1] = i;Below is the implementation of above approach:
[1, 0, 1]
Time Complexity: O(N + Q * log(N)), where N is number of the elements in the input array and and Q is the number of queries.
Auxiliary Space: O(N)