604. Shortest Distance to Target Color
You are given an integer array colors of length n, where each element represents the color of a house.
- Each house is painted in one of three colors, denoted by integers 1, 2, or 3.
- For example, if colors[i] = 2, it means the i-th house is painted with color 2.
You are also given a list of queries, where each query is represented as [index, color]:
- index → the position of the house from which you are starting.
- color → the target color you are looking for.
For each query, you need to find the shortest distance from the house at position index to any other house that has the target color.
- The distance between two houses at indices i and j is defined as |i - j|.
- If there is no house painted with the target color, return -1 for that query.
Your task is to return an array of results where result[i] is the answer for the i-th query.
Example 1:
Input: colors = [1,1,2,1,3,2,2,3,3], queries = [[1,3],[2,2],[6,1]]
Output: []
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.
Now Your Turn!
Pick the correct output for the given inputInput: colors = [2,1,2,2,1], queries = [[0,3],[3,2],[4,2]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= n <= 5*104
- colors[i] is 1, 2 or 3
- 1 <= queries.length <= 104
- 0 <= index < n
- 1 <= color <= 3